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.
Related
I have this code for a DAO - Database
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sqlinsert As String
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("[Number]") & "') "
DoCmd.RunSQL (sqlinsert)
When I run this, the Number will often be to a large decimal place, implying the need for Round(,2) or Format(, " #.00").
However, this code does not function.
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & rs("Format([Number], "#.00")") & "') "
Any ideas as to what the code should be?
sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Number]) Values ('" & Format(rs("[Number]"), "#.00") & "') "
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.
I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")
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.
I have an assignment to build a basic database driven e-commerce site. I have a home page, a products page, an orders page, an order confirm page, a shopping cart page and a view current orders page. The site uses an Access database with three tables.
A Customer table, with all of the customer details, (FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode)
A Products table, with all the product information, (ProductID, ProductName, Price, ProductType, Images, ProductDescription).
And an Orders table which contains CustomerID and ProductID.
I'm trying to create an INSERT statement on the orders page so that when the customer inserts their details and presses the submit button the customers table will have a new record inserted. I also want this to create an entry in the orders table and redirect the client to the order confirm page which will display the details of the order.
Here is my code which runs when the submit button is clicked on the order form.
EDIT I've fixed the error with the missing apostrophe. Attempting to insert using two sql commands as I've been told that access databases can't handle two at once. Still getting an error though.
Protected Sub btnAddRecord_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strEmailAdd As String
Dim intCardNo As String
Dim strCardEx As String
Dim intSortCode As String
Dim strDeliveryAdd As String
Dim strPostCode As String
Dim intProductID As Integer
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strEmailAdd = tbxEmailAdd.Text
intCardNo = tbxCardNo.Text
strCardEx = tbxCardEx.Text
intSortCode = tbxSortCode.Text
strDeliveryAdd = tbxDeliveryAdd.Text
strPostCode = tbxPostcode.Text
intProductID = ddlProduct.SelectedValue
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("KingToots.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "INSERT INTO Orders(ProductID) " & "Values ('" & intProductID & "');"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customer.* FROM Customer ORDER BY Customer.CustomerID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxEmailAdd.Text = ""
tbxCardNo.Text = ""
tbxCardEx.Text = ""
tbxSortCode.Text = ""
tbxDeliveryAdd.Text = ""
tbxPostcode.Text = ""
End Sub
You're missing the closing quotes at the end of this line:
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & ");"
About the obvious SQL injection problem, switching to parameters would be the best way to do it (and you'd never have your original issue if you did, parameters don't use quotes), but at the very least run a replace on your strings to replace ' with '' so your program doesn't just die if you get a customer called O'Neil.
He is correct, you don't want to do this you will get sql injection. But here is the solution to your problem anyway.
The problem is not in the last sql statement but in the previous one.
'" & strPostCode & " is missing the last single quote.
it should read:
'" & strPostCode & "');