“syntax error in INSERT INTO statement” - vb.net

I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement
Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("?", txtid)
.Parameters.AddWithValue("?", txtuser)
.Parameters.AddWithValue("?", txtpass)
.ExecuteNonQuery()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Could anyone help me?

Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Dim cmd As New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#ID", txtid)
.Parameters.AddWithValue("#Username", txtuser)
.Parameters.AddWithValue("#Password", txtpass)
.Open()
.ExecuteNonQuery()
.Close()
End With
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(#ID,#Username,#Password)"
Using con As New OleDbConnection(ConnectionStringHERE)
Using cmd As New OleDbCommand
Dim cmd As New OleDbCommand
cmd.Connection = con
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#ID", txtid)
cmd.Parameters.AddWithValue("#Username", txtuser)
cmd.Parameters.AddWithValue("#Password", txtpass)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
Try
InsertLogin()
MsgBox("The Data Has Been Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Here, I used cmd. syntax, it is no different then using With.

You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

Related

SQL (INSERT INTO) COMMAND DOES NOT WORK IN OLEDB IN VB.NET

I want to update in the "CIU" column in the database "GSDTS" and retrieve the data or values from the database "IFGTS" in the column "PRSOBNET" based on the conditions of the "ITM" column and the "GDN" column or warehouse. Do I have to do sql update or insert to please recommend the solution because I sql command in the code does not work at all and how can the sql command solution work?
thanks
jack
Sub InsertIntoGsdts()
Try
Dim sql As String = "INSERT INTO GSDTS (CIU) SELECT t1.PRSOBNET FROM IFGTS t1 WHERE NOT EXISTS(SELECT ITM FROM GSDTS t2 WHERE t2.ITM = t1.ITM) AND GDN = 'A.04.01.002.001'"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
Private Sub SQL2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SQL2.Click
InsertIntoGsdts()
fillDataGridView1()
End Sub
I found a solution according to the link below
Here's a link!
Sub InsertIntoGsdts()
Try
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2 on t1.[ITM] = t2.[ITM] set t1.[CIU] = t2.[PRSOBNET] WHERE GDN = 'A.04.01.002.001'"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Catch myerror As Exception
MessageBox.Show("Error: " & myerror.Message)
End Try
End Sub
Private Sub SQL2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SQL2.Click
InsertIntoGsdts()
fillDataGridView1()
End Sub

Update a database record

I use following code to update database record after retrieving data to the text boxes via a datagridview.
But this gives me an exception as object reference not set to an instance of the object. Please help
Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridViewUserType.CellClick
Dim i As Integer
i = DataGridViewUserType.CurrentRow.Index
If i >= 0 Then
Me.txtBoxID.Text = DataGridViewUserType.Item(0, i).Value
Me.txtBoxUserType.Text = DataGridViewUserType.Item(1, i).Value
Else
MessageBox.Show("Empty Row Clicked")
End If
End Sub
Private Sub btnUserTypeUpdate_Click(sender As Object, e As EventArgs) Handles btnUserTypeUpdate.Click
Try
con.Open()
cmd.Connection = con
cmd.CommandText = "UPDATE dbo.User_Type SET Type = #tp WHERE Type_ID = #ID"
cmd.Parameters.AddWithValue("#ID", txtBoxID.Text)
cmd.Parameters.AddWithValue("#tp", txtBoxUserType.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successfully Updated")
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Update Records")
Finally
con.Close()
btnUserTypeSave.Show()
txtBoxID.Clear()
txtBoxUserType.Clear()
End Try
End Sub
Thankz Fabio
The error was with "cmd"
I just put Dim cmd As SqlCommand = New SqlCommand before using it and now it is functioning.
Thankz All

returning select value using Visual Basic 2010 oleDB

I'm trying to read a excel cell with visual basic 2010 ( I'm really new to this) and I think I finally did it BUT I have no clue how to return the result.
It should end up in the clipboard or msgBox from there I'll find my way :D
I searched for two hours now but didnt find the solution... please help me
Thanks
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;extended properties=excel 8.0;"
cn.Open()
With cm
.Connection = cn
.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
.ExecuteNonQuery()
End With
cn.Close()
MsgBox(????)
End Sub
EDIT: her is the updated code. I get "Could not find installable ISAM
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;extended properties=excel 12.0;HDR=Yes"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:C20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
EDIT: That's what worked for me:
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT Service FROM [ccs$] WHERE id='" & ComboBox1.SelectedItem & "'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
Welcome to SO. In the future you should show us all of your code. Since you tagged OleDB and vb.net, the following implements what you are trying to accomplish. I included the Form Class so the Imports statements could be shown, but you can just copy and paste the click event code after insuring you Class includes the Imports. Note, I have not tested this code but it should work. Let me know if you need clarification or additional help.
Imports System.Data.OleDb
Public Class Form1
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim con As New OleDbConnection
Try
Using con
'added HDR=No to the extended properties of the connection string
' **EDIT**
con.ConnectionString = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\marcelf\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplicat'ion1\bin\Debug\DB.xls;Mode=3;User ID=Admin;Password=;Extended Properties=Excel 8.0"
con.Open()
Using cmd = New OleDbCommand
cmd.Connection = con
cmd.CommandText = "SELECT * FROM [ccs$C1:B20] WHERE 'id' = 'German'"
Using oRDR As OleDbDataReader = cmd.ExecuteReader
While (oRDR.Read)
MsgBox(oRDR.GetValue(0)) 'gets the first returned column
End While
End Using
con.Close()
End Using
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
con.Close()
End Try
End Sub
End Class

using CheckedListBox in vb.net2008

In vb.net 2008, How To insert Multiple selected Data from Checkedlistbox to Database sql server 2005?
My Code is
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Cn.Close()
Cn.Open()
Try
cmd.CommandText = "insert into Module_Control_tbl (empl_ID,Module_ID) Values('" & ComboBox1.SelectedValue & "','" & CheckedListBox1.SelectedValue & "')"
ComboBox1.Focus()
cmd.Connection = Cn
cmd.ExecuteNonQuery()
MsgBox("Assign Module Successfully to Employee")
Form7_Load(sender, e)
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("contact to Your System Administrator")
End Try
Cn.Close()
You should just iterate through the CheckedItems collection.
Furthermore, you should always use parameters to avoid SQL injection.
Here is an example:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using cn As New SqlConnection("Connection String")
cn.Open()
Dim sb As New StringBuilder
sb.AppendLine("INSERT INTO Module_Control_tbl")
sb.AppendLine("(empl_ID, Module_ID)")
sb.AppendLine("VALUES")
sb.AppendLine("(#empl_ID, #module_ID)")
For Each item In CheckedListBox1.CheckedItems
Using cmd As New SqlCommand(sb.ToString, cn)
cmd.Parameters.AddWithValue("#empl_ID", ComboBox1.SelectedValue.ToString)
cmd.Parameters.AddWithValue("#module_ID", item.ToString)
cmd.ExecuteNonQuery()
End Using
Next
End Using
End Sub

Data updation and deletion error

I have a DataGrid and many text fields to add data into the database. When i add a new data, it gets updated in the database and in the data grid.But when i delete the data, it gets deleted only from the database. It doesn't get updated in the data grid.
When i try to update the data, it updates only one record at a time.when i try for another record it gives me a error "The variable name '#date' has already been declared. Variable names must be unique within a query batch or stored procedure." I have to close and reopen the form to update a new record.
Imports System.Data.SqlClient
Public Class Form
Dim con As New SqlClient.SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Dim ds As DataSet
Dim da As SqlDataAdapter
Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DataSet11)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles newbtn.Click
If RegNoTextBox.Text <> "" Then
cmd.Connection = con
con.Open()
cmd.CommandText = "insert into WaterProofing(Date,RegNo) values ('" & DateDateTimePicker.Value & "','" & RegNoTextBox.Text & "')"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
Else
MessageBox.Show("Please enter registration number")
End If
End Sub
//updation
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
cmd.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
cmd.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
cmd.Connection = con
con.Open()
cmd.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Updated!")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
cmd.Connection = con
con.Open()
cmd.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
cmd.ExecuteNonQuery()
Call showdata()
con.Close()
MessageBox.Show("Details Deleted!")
End Sub
Sub showdata()
SqlDataAdapter1.Fill(DataSet11, "WaterProofing")
With DataGridView
.Update()
End With
End Sub
End Class
Please help me in deletion and updating.
You're adding parameters before declaring CommandText at Button2_Click
Try it in this way:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles editbtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "update WaterProofing set RegNo= #regno where date=#date"
command.Parameters.AddWithValue("#date", DateDateTimePicker.Value)
command.Parameters.AddWithValue("#regno", RegNoTextBox.Text)
command.ExecuteNonQuery()
con.Close()
Call showdata()
MessageBox.Show("Details Updated!")
Catch ex as Exception
MessageBox.Show(ex.Message)
End try
End Sub
UPDATE
Basically you have to do the same thing when you load the DataGridView for the first time in order to refresh the DataGridView with the current data from database after deleting or updating records, so your ShowData Sub might look something like this
Private Sub ShowData()
Dim Connection As SqlConnection
Connection = New SqlConnection("YourConnectionString")
Try
Connection.Open()
Dim SQL As String = "SELECT Field1, Field2, Field3 FROM Table"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView.DataSource = DS.Tables(0)
DataGridView.Refresh()
Catch ex As Exception
MessageBox(ex.Message)
Finally
Connection.Close()
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles deletebtn.Click
Try
Dim command As New SqlCommand
con.Open()
command.Connection = con
command.CommandText = "delete from WaterProofing where date='" & DateDateTimePicker.Value & "'"
command.ExecuteNonQuery()
con.Close()
Call ShowData_Delete()
MessageBox.Show("Details Deleted!")
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
End Try
End Sub
Private Sub ShowData_Delete()
Dim Connection As SqlConnection
Try
Connection = New SqlConnection("Server = DEL-PC; Database=Shj; Trusted_Connection=yes;")
Connection.Open()
Dim SQL As String = "SELECT * from WaterProofing"
Dim DS As New DataSet
Dim Adapter As New SqlDataAdapter(SQL, Connection)
Adapter.Fill(DS)
DataGridView1.DataSource = DS.Tables(0)
DataGridView1.Refresh()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
Connection.Close()
End Try
End Sub