vb.net Syntax error in INSERT INTO Statement with access - sql

I'm getting an error during my insert can someone take a look?
Table:
VB.NET
Dim Name As String = txtName.Text
Dim JoinDate As String = dpJoinDate.Value
Dim DOB As String = dpDOB.Value
Dim ParentsName As String = txtParentsName.Text
Dim School As String = txtSchool.Text
Dim STD As String = txtSTD.Text
Dim Address As String = txtAddress.Text
Dim EMail As String = txtEMail.Text
Dim Mobile1 As String = txtMobile1.Text
Dim Mobile2 As String = txtMobile2.Text
Dim DurationStart As Date = dpDurationStart.Value
Dim DurationEND As Date = dpDurationEND.Value
Dim Fees As Decimal = Decimal.Parse(0.0)
Dim MaterialFees As Decimal = Decimal.Parse(0.0)
Dim LateFees As Decimal = Decimal.Parse(0.0)
Dim NextRenewal As Date = dpNextRenewal.Value
Dim Centre As String = cbCentre.Text
Dim Coach As String = cbCoach.Text
Dim picture As String = lblFileName.Text
Try
Fees = Decimal.Parse(txtFees.Text)
Catch
End Try
Try
MaterialFees = Decimal.Parse(txtMaterialFees.Text)
Catch
End Try
Try
LateFees = Decimal.Parse(txtLateFees.Text)
Catch
End Try
Dim Cmd As OleDbCommand
Dim SQL As String
Dim objCmd As New OleDbCommand
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./AcademyDatabase.accdb;Persist Security Info=False;")
SQL = "INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('" _
& Name & "','" _
& JoinDate & "','" _
& DOB & "','" _
& ParentsName & "','" _
& School & "','" _
& STD & "','" _
& Address & "','" _
& EMail & "','" _
& Mobile1 & "','" _
& Mobile2 & "','" _
& DurationStart & "','" _
& DurationEND & "','" _
& Fees & "','" _
& MaterialFees & "','" _
& LateFees & "','" _
& NextRenewal & "','" _
& Centre & "','" _
& Coach & "','" _
& picture & "'," _
& "0)"
Cmd = New OleDbCommand(SQL, Con)
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
Dim rowCount As Integer = 0
Try
rowCount = objCmd.ExecuteNonQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Sql:
"INSERT INTO Student (FullName,JoinDate,DOB,ParentsName,School,STD,Address,EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees,MaterialFees,LateFees,NextRenewal,Centre,Coach,Image,DropOut) VALUES ('','3/13/2014','1/1/1900','','fadsasdffdas','','','','','','1/1/1900','1/1/1900','0','0','0','1/1/1900','','','',0)"

IMAGE is a reserved keyword. If you want to use it for a column name, then your need to encapsulate it with square brackets
"INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) VALUES ...."
If you are still able to do so, I suggest to change the name of that column to a NON reserved keyword, otherwise you will alway have this problem when you try to use that column.
Said that, please, read about parameterized queries. Your code has a big problem and it is called SQL Injection (not to mention the parsing problems for strings, date and decimals)
SQL = "INSERT INTO Student " & _
"(FullName,JoinDate,DOB,ParentsName,School,STD,Address," & _
"EMail,Mobile1,Mobile2,DurationStart,DurationEND,Fees," & _
"MaterialFees,LateFees,NextRenewal,Centre,Coach,[Image],DropOut) " & _
"?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)"
Con.Open()
objCmd = New OleDbCommand(SQL, Con)
objCmd.Parameters.AddWithValue("#p1", Name)
objCmd.Parameters.AddWithValue("#p2", JoinDate)
.... add the other missing parameters with their values.....
objCmd.Parameters.AddWithValue("#p18", picture)
Dim rowCount As Integer = 0
rowCount = objCmd.ExecuteNonQuery()

Related

how do I refresh gridview after adding new row?

I made several research but cannot figure out the problem. I can add, remove or edit rows from database in the code. However, I could not refresh the grid.
I mean, when I add new row to gridview, it doesn't appear in it. After I recompile the code it appears. How can I refresh the gridview?
Dim strSQL = "SELECT * FROM FIXEDCARD WHERE STKCODE = '" & TextEdit1.Text & "'"
objCon.Close()
Dim sqlCmd As New SqlCommand(strSQL, objCon)
objCon.Open()
Dim dreader As SqlDataReader
dreader = sqlCmd.ExecuteReader
If dreader.Read Then
'Dim stk_ As String = dreader.GetString(dreader.GetOrdinal("STKCODE")).ToString()
DevExpress.XtraEditors.XtraMessageBox.Show("already exists", "Info!", MessageBoxButtons.OK)
objCon.Close()
Else
dreader.Close()
strSQL = "INSERT INTO FIXEDCARD(STKCODE, STKEXP, AUTHCODE, GRPCODE, SPECODE" & _
", SPECODE2, SPECODE3, SPECODE4, SPECODE5, AMORTRATIO, AMORT," & _
"PURCH, SALES, RETUR, UNIT) VALUES('" & TextEdit1.Text & "'," & _
"'" & TextEdit2.Text & "', '" & TextEdit3.Text & "'," & _
"'" & TextEdit4.Text & "', '" & TextEdit5.Text & "'," & _
"'" & TextEdit6.Text & "', '" & TextEdit7.Text & "'," & _
"'" & TextEdit8.Text & "', '" & TextEdit9.Text & "'," & _
"'" & TextEdit10.Text & "', '" & TextEdit11.Text & "'," & _
"'" & TextEdit12.Text & "', '" & TextEdit13.Text & "'," & _
"'" & TextEdit14.Text & "', '" & TextEdit15.Text & "') "
sqlCmd = New SqlCommand(strSQL, objCon)
sqlCmd.ExecuteNonQuery()
objCon.Close()
End If
RefreshGrid()
Me.Close()
And also I try to write a refresh function that will refresh the gridview when I call it each button. However, I have been making a mistake but could not recognize it.
Public Sub RefreshGrid()
Dim T As New DataTable
Dim strSQL = "Select * From FIXEDCARD"
Dim sqlCmd As New SqlCommand(strSQL, objCon)
T = CType(sqlCmd.ExecuteNonQuery(), System.Data.DataTable)
GridView1.DataSource = T
End Sub
Public Function FillDataSet(query As String, ByVal ParamArray para() As Object) As DataTable
dim _transaction As SqlTransaction
Dim _command As SqlCommand
_command = New SqlCommand(query, yourConnection)
_ds = New DataSet
_sqlda = New SqlDataAdapter(_command )
_command.Transaction = _transaction
For i = 0 To para.Count - 1
_command.Parameters.AddWithValue("#" & i, para(i))
Next
_sqlda.Fill(_ds)
return _ds.tables(0)
End Function
call it
GridControl1.datasource = Nothing
GridControl1.datasource = FillDataSet(YourInsertQuery,YourParam)
GridControl1.RefreshDataSource()
You are using a "Non-Query" in the refresh. This doesn't return a table value.
Try using the SqlCommand.ExecuteReader method.
Reference: https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx

How to insert character in charset UTF-8 on System.Data.SqlClient

First ,I'm sorry about my English
I have problem insert character to my local DB ,character is Thai language
This is my module
Imports System.Data
Imports System.Data.SqlClient
Module Module_all
Friend strConnString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\VB\Bank_Project\DB\DB1.mdf;Integrated Security=True;Connect Timeout=1000;characterEncoding=UTF-8"
Friend objCmd As New SqlCommand
Friend objConn As New SqlConnection
Friend sql As String
End Module
Thank a lot for your answer
sql = "SELECT COUNT(*) FROM Employee "
Dim cmd As New SqlCommand(sql, objConn)
Dim intNumRows As Integer = cmd.ExecuteScalar()
Dim Id As Integer = intNumRows + 1
Dim op As String
If (ListBox1.SelectedIndex = 0) Then
op = "ออมทรัพย์"
ElseIf (ListBox1.SelectedIndex = 1) Then
op = "ฝากประจำ"
End If
cmd = New SqlCommand("Insert into Customer Values('" & Id & "','" & Text_pass.Text.Trim() & "','" & Text_money.Text.Trim() & "','" & Text_name.Text.Trim() & "','" & Text_ad.Text.Trim() & "','" & Text_mail.Text.Trim() & "','" & Text_tel.Text.Trim() & "','" & Text_money.Text.Trim() & "')", objConn)
cmd.ExecuteNonQuery()

Inserting the current datetime in vb.net(DateTime to String Conversion)

I'm suppose to enter datatime to the database by passing this query
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyyMMddHHmmss")
I pass the "strDate" to the query,data type of my database table is datetime
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & regDate & "')")"
but it's getting error saying that
conversion failed when converting date and/or time from character string.
Help me to solve this problem
Dim regDate As DateTime = DateTime.Now
Dim strDate As String = regDate.ToString("yyyy-MM-dd HH:mm:ss")
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
you have to pass strDate in query.Always use paremeterized query to avoid SQL injection
objcon.DoExecute("INSERT INTO DistributorF VALUES('" & txtDisId.Text & "',
'" & txtDisNm.Text & "','" & txtDisAdd.Text & "',
'" & txtDisTele.Text & "','" & txtDisEmail.Text & "','" & strDate & "')")"
May this works for you, at least it works for me on an acces db
Try
Dim cn As New OleDbConnection("your conection string here")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into UserInfo(Date) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim date As OleDbParameter = New OleDbParameter("#d1", OleDbType.Date, 15)
date.Value = DateTimePicker1.Text.ToString()
cmd.Parameters.Add(date)
If cmd.ExecuteNonQuery() Then
cn.Close()
MsgBox("successfully... ", MsgBoxStyle.Information, "Record Saved")
Else
MsgBox("failed... ", MsgBoxStyle.Critical, "Registration failed")
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Error")
Exit Sub
End Try
i hope this helps you,
regards Tom

Updating Access Database using UPDATE SQL statement in VBA

Can someone take a look a the stSQL string and help me fix the syntax error I am getting associated with the UPDATE statement?
Run-time error '-2147217900 (8004e14)': Syntax error in UPDATE statement.
I have a rudimentary understanding of SQL and don't seem to understand where I have gone wrong.
I want to update the fields of Table 1 if the FileName UserForm value matches a FileName field in the Access Db.
Thanks
Public Sub UpdateDatabaseEntry()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim FileName As String
Dim Nickname As String
Dim RecipientName As String
Dim RecipientRelationship As String
Dim Summary As String
Dim Noteworthy As String
Dim PreparedBy As String
FileName = UserForm1.FileNameTextBox.Text
Nickname = UserForm1.NicknameTextBox.Text
RecipientName = UserForm1.RecipientNameTextBox.Text
RecipientRelationship = UserForm1.RecipientRelationshipComboBox.Text
Summary = UserForm1.SummaryTextBox.Text
Noteworthy = UserForm1.NoteworthyCheckBox.Value
PreparedBy = UserForm1.PreparedByTextBox.Text
stDB = "Data Source= E:\MyDb.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
//Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
//SQL Statement telling database what to do
stSQL = "UPDATE Table1" & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "', " & _
"WHERE FileName= '" & FileName & "'"
cn.Execute stSQL
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
At least one problem is caused by lack of spaces in the query. So your query started UPDATE Table1set.
stSQL = "UPDATE Table1 " & _
"SET Nickname= '" & Nickname & "', RecipientName= '" & RecipientName & "', " & _
"RecipientRelationship= '" & RecipientRelationship & "', Summary= '" & Summary & "', " & _
"Noteworthy= '" & Noteworthy & "', PreparedBy= '" & PreparedBy & "'" & _
"WHERE FileName= '" & FileName & "'"
If this doesn't fix the problem. Then edit your question with the value of stSQL after the variable substitution.
EDIT:
As TS points out, another problem is the , before the where (fixed above).

How to insert customer details into Orders table

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 & "');