Private Sub submit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles submit.Click
Dim con As New OleDb.OleDbConnection
Dim cmd As New OleDb.OleDbCommand
Dim dbProvider As String = "PROVIDER = Microsoft.Jet.OleDb.4.0;"
Dim dbSource As String = "DATA SOURCE =" & Application.StartupPath & "\hospital.mdb"
con.ConnectionString = dbProvider & dbSource
If Not con.State = ConnectionState.Open Then
con.Open()
End If
cmd.Connection = con
cmd.CommandText = "INSERT INTO userdata(masterid, pname, aname, dob, bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone)" & _
"VALUES ('" & Me.masterid.Text & "','" & Me.pname.Text & "','" & Me.aname.Text & "','" & Me.dob.Text & "','" & Me.bloodgroup.Text & "','" & _
Me.address.Text & "','" & Me.gender.Text & "','" & Me.referto.Text & "','" & Me.designation.Text & "','" & Me.relh.Text & "','" & Me.mpass.Text & "','" & _
Me.ward.Text & "','" & Me.bed.Text & "','" & Me.zone.Text & "')"
cmd.ExecuteNonQuery()
con.Close()
End Sub
And the values going in the cmd.Commandtext is
"INSERT INTO userdata(masterid, pname, aname, [dob], bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone)VALUES ('305201323114','fsdfsd','sdfsd','5/29/2013','AB+','sdfsd','Male','sdfsd','sdfsd','sdfsd','sdfdsf','sdfsdf','dfds','North East Zone')"
One potential problem with the SQL statement you generated is '5/29/2013'. Jet normally uses hash marks # (not single quotes ') as date delimiters so you may be getting a "Type mismatch" error by trying to assign a string to a Date/Time field.
In any case, you can avoid these kinds of problems (and others, like SQL Injection) by using a parameterized query. It would go something like this:
cmd.CommandText = "INSERT INTO userdata (masterid, pname, aname, dob, bloodgroup, address, gender, referto, designation, relh, mpass, ward, bed, zone) " & _
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
cmd.Parameters.AddWithValue("?", Me.masterid.Text)
cmd.Parameters.AddWithValue("?", Me.pname.Text)
cmd.Parameters.AddWithValue("?", Me.aname.Text)
' [... and so on ...]
cmd.Parameters.AddWithValue("?", Me.zone.Text)
cmd.ExecuteNonQuery()
Do yourself a favour and start using this method instead of "gluing together" long strings of troublesome (and vulnerable!) SQL code.
Related
I am creating a simple UserID/Password access database for a Visual Basic program.
Everything works except adding a new user.
My text box Objects are linked to my database but I keep getting this error when I try to add my new user.
Error: An unhandled exception of type
'System.Data.OleDb.OleDbException' occurred in System.Data.dll
HERE IS MY CODE:
Imports System.Data.OleDb
Public Class newUser
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
Private Sub btnNewUser_Click(sender As Object, e As EventArgs) Handles btnNewUser.Click
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\PasswordCheck.accdb"
Dim conn As OleDbConnection = New OleDbConnection
conn.ConnectionString = connString
conn.Open()
Dim SaveNew As String = "INSERT INTO [Password] (UserId, Password, firstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
Dim cmd As New OleDbCommand
cmd.Connection = conn
With cmd
.CommandText = SaveNew
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("You have been added to our Database")
txtUserID.Text = ""
txtPassword.Text = ""
txtFirst.Text = ""
txtLast.Text = ""
conn.Close()
End Sub
Private Function SaveNew() As String
Throw New NotImplementedException
End Function
End Class
Password is a reserved word also for a field, so:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values ('" & txtUserID.Text & "','" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
And further, if UserID not is text, then no quotes:
Dim SaveNew As String = "INSERT INTO [Password] (UserId, [Password], FirstName, LastName) Values (" & txtUserID.Text & ",'" & txtPassword.Text & "','" & txtFirst.Text & "','" & txtLast.Text & "')"
That said, try to explorer how to carry this out using parameters. Much more fun than SQL concatenation.
I have a query but when I try it's giving me some error on a date or any other variable. I can't get it right. Can you please help me? Here is the code:
Dim tax As Integer = 10
Dim APPROVED As Boolean = 1
Dim admin As String = "admin"
sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES ('" & TextBox2.Text & "', #" & DateTimePicker1.Value.Date & "#, '" & TextBox1.Text & "', #" & DateTimePicker2.Value.Date & "#, " & TextBox3.Text & ", '" & ComboBox1.SelectedItem.ToString & "', '" & ComboBox2.SelectedItem.ToString & "', " & tax & ", '" & APPROVED & "', '" & admin & "', #" & DateTimePicker1.Value.Date & "#);"
sqlquery.ExecuteNonQuery()
Now I am getting this error:
Data type mismatch in criteria expression.
Which date format want to follow?
Use parameterized queries.
What you have is crazy vulnerable to sql injection attacks. Parameterized queries will fix that issue and your formatting issue:
Dim tax As Integer = 10
Dim APPROVED As Boolean = 1
Dim admin As String = "admin"
sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
sqlquery.Parameters.Add("?", OleDbType.VarWChar, 10).Value = TextBox2.Text
sqlquery.Parameters.Add("?", OleDbType.Date).Value = DateTimePicker1.Value.Date
'...
sqlquery.ExecuteNonQuery()
Data type mismatch in criteria expression. You are trying to insert the wrong data-type into your database. Double check your data types in your database. If its a date, insert a date, if it's text, insert text.
Further more, string concatenation make it harder to find errors and it also leaves your open to SQL injection.
Here is a simple example of using parameters:
Using con As New OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
"Data Source = " & My.Settings.dbpath
con.Open()
Dim sql_insert As String = "INSERT INTO Table_Name (Order_ID, Customer_Name) " & _
"VALUES " & _
"(#entry_ref, #customer_name);"
Dim sql_insert_entry As New OleDbCommand
con.Open()
With sql_insert_entry
.Parameters.AddWithValue("#entry_ref", entry_ref)
.Parameters.AddWithValue("#customer_name", tb_new_entry_customer_name.Text.Trim())
.CommandText = sql_insert
.Connection = con
.ExecuteNonQuery()
End With
con.close()
End Using
As you can see, it's easy to follow and protects your database at the same time.
I get the following error: Operator '&' is not defined for types 'String' and 'System.Windows.Forms.TextBox'. :
in the following line of code:
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
here is the code :
Private Sub addbtn_Click(sender As Object, e As EventArgs) Handles addbtn.Click
Dim cmd As New OleDbCommand
If Not connection.State = ConnectionState.Open Then
connection.Open()
End If
cmd.Connection = connection
' add data to table
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
cmd.ExecuteNonQuery()
'refresh data in list
'close connection
connection.Close()
End Sub
You have to use Me.adduseridtxtbox.Text (which gets the value of the TextBox) rather than the TextBox directly.
Also, please, please, please read about OleDbParameter and how to use these parameters with OleDbCommand to prevent injection. Microsoft even provides examples.
Currently your code is extremely dangerous if you are letting users fill this form out themselves, as they have full control over your database. Regardless, using OleDbParameter is a good practice to get into. You appear to be handling social security numbers here -- your users deserve some form of security.
You should try to use/declare parameters in your query.
For example:
cmd.CommandText = ("INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) " & _
"VALUES (#uid, #pw, #fn, #ln, #job, #ssn)")
With cmd.Parameters
.Clear()
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("pw", addpasswordtxt.Text
.AddWithValue("fn", addfirstnametxt.Text)
.AddWithValue("ln", addlastnametxt.Text)
.AddWithValue("job",jobcbox.SelectedValue)
.AddWithValue("ssn", addssntxt.Text)
End With
cmd.ExecuteNonQuery()
Your SQL Statement is not proper. How do you use an object as a string? It should be
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES ('" & Me.adduseridtxtbox.Text & ",'" & Me.addpasswordtxt.Text & ",'" & Me.addfirstnametxt.Text & ",'" & Me.addlastnametxt.Text & ",'" & Me.jobcbox.Text & ",'" & Me.addssntxt.Text & "')"
Use parametrised query to prevent SQL Injections and make safe your database system from malicious users.
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
When the code is executed and error is thrown, but there is no visible problem that i can see. Help!
The word PASSWORD is reserved in MS-Access.
You need to use square brackets around that name (Or change it to something different)
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (......
Said that, please use a parameterized query to build sql commands.
A string concatenation like yours is easily attacked by hackers using SQL Injection
Also, if the username or password contains a single quote, the resulting sql text built using string concatenation will be invalid.
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (?, ?)"
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
cmd.Parameters.AddWithValue("#p1",txtUsername.Text);
cmd.Parameters.AddWithValue("#p2",txtEncryptedPassword);
cmd.ExecuteNonQuery();
You forgot parentheses:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
try this code:
Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonCode _
& "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')"
Do it like that but change to your names.
Declare the values of text boxes as strings and just use those.
your doing () this mistake and you should must add:
your code:
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
you should must change code following as:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
update1:
"INSERT INTO `test`.`users` ( `username`, `password`) " & _
"VALUES ('" & txtUsername.Text & "', '" & txtPassword.Text & "');"
update2:
"INSERT INTO users ( `username`,`password`)VALUES(#txtUsername.Text,#txtPassword.Text);"
"INSERT INTO users (Username,Password)VALUES(?,?);"
note:test means database name you should change your databasename.
This question already has answers here:
Syntax error when executing INSERT INTO statement
(4 answers)
Closed 8 years ago.
When I try cmd.ExecuteNonQuery() I get an error saying "Syntax error in INSERT INTO statement."
I posted this same problem yesterday... can someone help me again?
Private Sub btnadd1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd1.Click
Dim cmd As New OleDb.OleDbCommand
Dim Printlist1 As New DataTable
If Not con.State = ConnectionState.Open Then
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=c:Database11.accdb"
con.Open()
cmd.Connection = con
End If
If Me.text1.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, Description, Company, Department, Location, User, SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(#StickerCode, #Description, #Company, #Department, #Location, #User, #SerialNumber, #DatePurchased, #Tagable, #Quantity, #Brand, #Model)"
cmd.Parameters.AddWithValue("#StickerCode", Me.text1.Text)
cmd.Parameters.AddWithValue("#Description", Me.text2.Text)
cmd.Parameters.AddWithValue("#Company", Me.text3.Text)
cmd.Parameters.AddWithValue("#Department", Me.text4.Text)
cmd.Parameters.AddWithValue("#Location", Me.text5.Text)
cmd.Parameters.AddWithValue("#User", Me.text6.Text)
cmd.Parameters.AddWithValue("#SerialNumber", Me.text7.Text)
cmd.Parameters.AddWithValue("#DatePurchased", Me.text8.Text)
cmd.Parameters.AddWithValue("#Tagable", Me.text9.Text)
cmd.Parameters.AddWithValue("#Quantity", Me.text10.Text)
cmd.Parameters.AddWithValue("#Brand", Me.text11.Text)
cmd.Parameters.AddWithValue("#Model", Me.text12.Text)
cmd = New OleDbCommand(cmd.CommandText, con)
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE Printlist1 " & _
" SET StickerCode='" & Me.text1.Text & _
", Description='" & Me.text2.Text & "'" & _
", Company='" & Me.text3.Text & "'" & _
", Department='" & Me.text4.Text & "'" & _
", Location='" & Me.text5.Text & "'" & _
", User='" & Me.text6.Text & "'" & _
", SerialNumber='" & Me.text7.Text & "'" & _
", DatePurchased='" & Me.text8.Text & "'" & _
", Tagable='" & Me.text9.Text & "'" & _
", Quantity='" & Me.text10.Text & "'" & _
", Brand='" & Me.text11.Text & "'" & _
", Model='" & Me.text12.Text & "'" & _
" WHERE text1=" & Me.text1.Tag
cmd.ExecuteNonQuery()
End If
RefreshData()
Me.btnclear1.PerformClick()
con.Close()
End Sub
Sticker Code Description Company Department Location User Serial Number Date Purchased Tagable Quantity Brand Model
User is a reserved word in Sql try placing it in Square Brackets like this [User]
cmd.CommandText = "INSERT INTO Printlist1(StickerCode, [Description], Company, Department, Location, [User], SerialNumber, DatePurchased, Tagable, Quantity, Brand, Model)" & _
" VALUES(#StickerCode, #Description, #Company, #Department, #Location, #User, #SerialNumber, #DatePurchased, #Tagable, #Quantity, #Brand, #Model)"