data is not inserted to database - sql

i tried to insert the data into database with this code
Public Sub AddUser()
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id='" & WorkerID_.Text & "'"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Dim da As New OleDbDataAdapter
con.open()
reader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows() Then
reader.Close()
con.close()
FailureText.Text = "User ID already exists!"
Else
reader.Close()
con.close()
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) VALUES "
InsertSQL &= "('" & WorkerID_.Text & "', "
InsertSQL &= "'Worker', "
InsertSQL &= "'12345', 1)"
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) VALUES (default,"
SqlUpdate &= "'" & WorkerID_.Text & "', "
SqlUpdate &= "'" & WorkerName.Text & "', "
SqlUpdate &= "'" & DoB.Text & "', "
SqlUpdate &= "'" & Address.Text & "', "
SqlUpdate &= "'" & Phone.Text & "', "
SqlUpdate &= "'" & Email.Text & "', "
SqlUpdate &= "'" & Company.SelectedValue & "', "
SqlUpdate &= "'" & PassNum.Text & "', "
SqlUpdate &= "'" & PassExp.Text & "', "
SqlUpdate &= "'" & VisaExp.Text & "', "
SqlUpdate &= "'No Visa', "
SqlUpdate &= "'" & WorkerID_.Text & "') "
Dim insertCommand As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim cmd1 As New OleDbCommand(InsertSQL, con.oleconnection)
Try
con.open()
cmd1.ExecuteNonQuery()
insertCommand.ExecuteNonQuery()
Catch
FailureText.Text = "Unable to add user"
Finally
con.close()
End Try
End If
Response.Redirect("Workers.aspx")
End Sub
the Insert into login part is working. the data is well inserted. but for the insert into worker part is not working. the data is not inserted into the table. the program shows no error and it still can work. what could possibly wrong with this?

Read another answer on OleDb I just answered on another post. You will be wide open to sql-injection too. Parmaeterize queries. By you concatenating strings to build one command, what if one value has a single-quote within the text entry. You are now hosed. What if someone puts malicious SQL commands and then deletes your records or entire table(s). Learn to parameterize your queries and also clean values, especially if coming from a web interface.
Your commands should probably be updated something like
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id= #parmUserID"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
cmd.Parameters.AddWithValue( "parmUserID", WorkerID_.Text )
Follow-suit with the Insert and update commands... parameterize them but using #variable place-holders in your commands.
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) "
InsertSQL &= " VALUES ( #parmUser, #parmRole, #parmPwd, #parmStatus )"
Dim cmdInsert As New OleDbCommand(InsertSQL, con.oleconnection)
cmdInsert.Parameters.AddWithValue( "parmUser", WorkerID_.Text )
cmdInsert.Parameters.AddWithValue( "parmRole", "Worker" )
cmdInsert.Parameters.AddWithValue( "parmPwd", "12345" )
cmdInsert.Parameters.AddWithValue( "parmStatus", 1 )
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) "
SqlUpdate &= " VALUES ( #parmID, #parmName, #parmDoB, etc... ) "
Dim cmdUpdate As New OleDbCommand(SqlUpdate, con.oleconnection)
cmdUpdate.Parameters.AddWithValue( "parmID", WorkerID_.Text )
cmdUpdate.Parameters.AddWithValue( "parmName", WorkerName.Text )
cmdUpdate.Parameters.AddWithValue( "parmDoB", DoB.Text )
-- etc with the rest of the parameters.
Final note. Make sure the data types you are trying to insert or update are of same type expected in the table. Such example is your "Birth Date" (DoB) field. If you are trying to insert as simple text, and it is not in an auto-converted format, the SQL-Insert might choke on it and fail. If you have a textbox bound to a DateTime type, then your parameter might be Dob.SelectedDate (such as a calendar control), or you could pre-convert from text to a datetime and then use THAT as your parameter value.
Other numeric values, leave as they are too, they should directly apply for the insert. You could also identify the AddWithValue() call the data type the parameter should represent (string, int, double, datetime, whatever)

You seem to have 12 parameters you wish to insert, and 13 arguments in the VALUES part of your insert query. is the Default seen in the values section below intentional?
INSERT INTO Worker (ID, ... VisaStatus) VALUES (default,"
ensure you have the correct number of parameters defined and added, then let us know, but i could be missing something else.

Related

INSERT INTO and UPDATE SQL using visual basic into access database

I'm working on my A Level coursework using VB forms as my front end and an Access database as the back end. I've tried loads of different ways but I can't get the program to update or insert data into the database.
I know for a fact the connection is fine because I've had no problem retrieving data from access into the program.
This the code for one of the forms:
(the database connection is in a separate form)
Access.ExecQuery("SELECT * FROM Exam;")
Dim user As String = TxtStudent.Text
Dim board As String = CmbBoard.Text
Dim instrument As String = CmbInstrument.Text
Dim grade As String = CmbGrade.Text
Dim result As String = CmbResult.Text
Access.ExecQuery("INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES ('" & user & "', '" & board & "', '" & instrument & ", " & grade & ", " & result & "');")
If Not String.IsNullOrEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
The error message says there is a syntax error on INSERT INTO statement.
Am i just being really stupid?
you are missing closing "'" for instrument '" & instrument & "', " . and also, just confirm the values for fields without single quotes(grade ) are numeric otherwise add single quotes
Your single and double parenthesis are a bit of a mess. This alone is a good reason to use parameters but it also protects you from malicious input by users. The important thing with Access is that you must add the parameters in the same order that the command uses them.
Dim cn As New OleDbConnection("Your Access connection string")
Dim s As String = "INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES (#User, #Instrument, #Board, #Grade, #Result);"
Dim cmd As New OleDbCommand(s, cn)
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
Double check the data types of the fields and adjust the code if they are not all strings.
In SQL Queries and statements , '(single quote) is used to pass a value of type string to any given parameter(or anything).You mistake was that you forgot to add ' in all the places.
"INSERT INTO Grade (Username, Instrument, Exam Board, Grade, Result) VALUES ('" & user & "', '" & board & "', '" & instrument & ", "'" & grade & "'", "'" & result & "'")"
This will solve it :)
However, one advice, don't give direct values in the statement itself,you are welcoming SQL-Injection.Rather,create parameters and values to them later :
Dim cmd as New SqlCommand("INSERT INTO Grade (Username)Values(#uname)",con)
cmd.Parameter.Add("#uname",SqlDbType.Vachar) = "abc"
Hope this helps to enrich your knowledge :)
You must try this!
Dim con As New OleDbConnection("Your Access connection string here")
Dim s As String = "INSERT INTO Grade ([Username], [Instrument], [Exam Board], [Grade], [Result]) VALUES (#User, #Instrument, #Board, #Grade, #Result)"
Dim cmd As New OleDbCommand(s, con)
con.Open()
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cmd.ExecuteNonQuery()
con.Close()
I hope it will works! :)
Dim con As New OleDbConnection("Your Access connection string here")
Dim s As String = "INSERT INTO Grade ([Username], [Instrument], [Exam Board], [Grade], [Result]) VALUES (#User, #Instrument, #Board, #Grade, #Result)"
Dim cmd As New OleDbCommand(s, con)
con.Open()
cmd.Parameters.AddWithValue("#User", TxtStudent.Text)
cmd.Parameters.AddWithValue("#Instrument", CmbInstrument.Text)
cmd.Parameters.AddWithValue("#Board", cmdBoard.Text)
cmd.Parameters.AddWithValue("#Grade", CmdGrade.Text)
cmd.Parameters.AddWithValue("#Result", CmdResult.Text)
cmd.ExecuteNonQuery()
con.Close()

Retrieve data from table a, insert into Table B along with other fields

I am trying to combine the two Sql Commands so that I can populate the data field with the text from the Select Command See below; I would like the text “Note Goes Here” to be replaced with the data from the selectcommand. However I am not sure how to do it.
Dim selectCommand As String = "Select Notes from Note Where NoteKey = " & lngNoteKey
strsql = "Insert into Activity (userName,pVisits,timeDate,data,flag)" _ & " Values('" & GetUserName() _ & "', '" & currentPage & "', '" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "', '" & "Note Text Goes Here" & "','" & "2" & "')"
I'm new to asp.net and vb and sql so be gentle
Generally speaking, any INSERT statement of the form
INSERT (a, b, c)
VALUES ( 'constant', 'constant', X from some table Y where Z)
can be replaced with
INSERT (a, b, c)
SELECT 'constant', 'constant', X
FROM Y
WHERE Z
So you'd want some SQL similar to this:
INSERT Activity (userName, pVisits, timeDate, data, flag)
SELECT #UserName, #PVisits, GETDATE(), Notes, 2
FROM Note
WHERE NoteKey = #NoteKey
You can use multiple queries on same command and use parameter to protect from sql injecttion:
Dim connection As New SqlConnection("Data Source=TEst//TEst;Initial Catalog=cMind_ProgramGuide;Persist Security Info=False;")
Dim strsql As String = "Insert into Activity (userName,pVisits,timeDate,data,flag) Select #userName,#pVisits,#timeDate,Notes,#flag from Note Where NoteKey = #note"
Dim Command As New SqlCommand(strsql, connection)
Command.Parameters.Add("#userName", SqlDbType.NVarChar).Value = GetUserName()
Command.Parameters.Add("#pVisits", SqlDbType.NVarChar).Value = currentPage
Command.Parameters.Add("#timeDate", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Command.Parameters.Add("#note", SqlDbType.NVarChar).Value = lngNoteKey
Command.Parameters.Add("#flag", SqlDbType.Int).Value = 2
connection.Open()
Command.ExecuteNonQuery()
connection.Close()

VB.Net 2013 (VB fail to search the access database)

I have this weird problem when I register using my system I developed in VB.NET, it does not allow me to login(in the login form) using the correct username and password I registered. However, when I manually input the username and password inside the Access database, I manage to login without any problem. Here are the codes of my login and register
Login
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\Users\lenovo\Documents\Visual Studio 2012\Projects\SDP user interface\SDP user interface\bin\Debug\SCPdatabase.accdb")
conn.Open()
sql = "Select * FROM Members WHERE Username ='" & txtusername.Text & "' AND [Password] ='" & txtpassword.Text & " ' "
cmd = New OleDbCommand(sql, conn)
dr = cmd.ExecuteReader()
If dr.HasRows Then
MessageBox.Show("Login Success")
Me.Hide()
Member_Page.Show()
Member_Page.lblwelcome.Text = "Welcome" & txtusername.Text
Else
MessageBox.Show("Login Failed")
End If
dr.Close()
conn.Close()
Register
Dim flag As Integer
MyConn.Open()
sql = "Insert INTO Members (Username,[IC],Email,PhoneNumber,FullName,[Password],Newsletter) values (' " & txtusername3.Text & "','" & txtic3.Text & "','" & txtemail3.Text & "','" & txtphone3.Text & "','" & txtname3.Text & "', ' " & txtpwd3.Text & " ',' " & cmb3.Text & " ')"
cmd = New OleDbCommand(sql, MyConn)
flag = cmd.ExecuteNonQuery()
If flag > 0 Then
MessageBox.Show(flag & " records added", "Add Records Successful", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
MyConn.Close() 'closes the connection
Please advice thnx
Your INSERT statement is adding whitespace characters to the values:
' " & txtusername3.Text & "'
^--- here
and
' " & txtpwd3.Text & " '
^--- here ^--- here
etc.
But then when you select from the table, you don't include them:
WHERE Username ='" & txtusername.Text & "' AND [Password] ='" & txtpassword.Text & " '
just here ---^
Get rid of the whitespace characters entirely, as they're changing the values from what you expect those values to be.
Or, better yet, use query parameters so you don't have to manually build these string values in the first place. (And, as a bonus, would close the enormous SQL injection vulnerability you currently have.)

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos

Multiple if statements, then, or else?

I'm having some problems getting a query to run based off another query. Here's the database diagram to give a little background. The primary keys for all the tables are automatically generated by identites. The first 2 insert statements (Donation and Food_Donation) work but I can't get the last insert into Donation_Details to work. Here's the code so far:
Dim con As New OleDbConnection(DBcon)
Try
Dim dr As OleDbDataReader
Dim command As New OleDbCommand("Insert into Donation (Donor_ID) VALUES ( " & txtDonNum.Text & "); Select ##Identity;")
con.Open()
command.Connection = con
dr = command.ExecuteReader
Dim Donation_ID As String = ""
If dr.Read() Then
Donation_ID = dr(0).ToString
Dim food As New OleDbCommand("Insert into Food_Donation (Date_Received, Donation_ID) Values ( '" & maskedreceived.Text & "', " & Donation_ID & "); Select ##Identity")
food.Connection = con
food.ExecuteNonQuery()
End If
Dim Food_ID As String = ""
If dr.Read() Then
Food_ID = dr(0).ToString
Dim food2 As New OleDbCommand("Insert into Donation_Details (Quantity, Unit, Expiration_Date, Food_ID, Storage_ID, Type_ID) Values ( " & txtQuantity.Text & ", '" & boxUnit.Text & "', '" & maskedexpire.Text & "', " & Food_ID & ", " & txtStorageID.Text & ", " & txtTypeID.Text & ")")
food2.Connection = con
food2.ExecuteNonQuery()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
con.Close()
End Try
End sub
I'm fairly correct my SQL statements are correct and it's just whether or not the last statements need to be an If or something else.
You should be using dr = food.ExecuteReader() rather than food.ExecuteNonQuery() if you want to reuse dr to acquire Food_ID?
I suspect your problem is that you're using If dr.Read() twice.
The dr.Read() method will move the reader forward to the next row but you are only selecting a single value in your initial query.
So, for example, your reader (being made from the insert) will return a single row value for the successful insert. Calling Read() on it will succeed but then move the row cursor to EOF causing subsequent Read() calls to return FALSE