VB.NET database data passing error - sql-server

I get the error message
"Error while inserting record o the table… Incorrect syntax near the
keyword ‘return’.Incorrect syntax near ‘,’ ."
Public Class Form10
Dim con As New SqlClient.SqlConnection
Dim cmd, com As New SqlClient.SqlCommand
Dim sqlda As New SqlClient.SqlDataAdapter
Dim ds As New DataSet
Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
con.ConnectionString = "data source=.\sqlexpress;initial catalog =pharmacy;Integrated Security =true"
Catch ex As Exception
MessageBox.Show(ex.Message, "Connection Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
End Try
End Sub
Private Sub btnclear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclear.Click
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
End Sub
Private Sub btnsearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
con.Open()
Try
sqlda = New System.Data.SqlClient.SqlDataAdapter("SELECT * FROM return where r_invoice_no='" & txtrinvo.Text & "'", con)
ds.Clear()
sqlda.Fill(ds, "return")
txtdcode.Text = ds.Tables("return").Rows(0).Item(0)
txtcreg.Text = ds.Tables("return").Rows(0).Item(1)
txtprice.Text = ds.Tables("return").Rows(0).Item(2)
txtqty.Text = ds.Tables("return").Rows(0).Item(3)
txttamount.Text = ds.Tables("return").Rows(0).Item(4)
DateTimePicker1.Text = ds.Tables("return").Rows(0).Item(5)
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
ProgressBar1.Visible = False
Catch ex As IndexOutOfRangeException
MsgBox("Type correct Return Invoice Number to search.." & ex.Message, MsgBoxStyle.Critical, "TRY AGAIN")
Finally
con.Close()
End Try
End Sub
Private Sub btnadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnadd.Click
con.Open()
Try
If txtdcode.Text = "" Or txtrinvo.Text = "" Or txtcreg.Text = "" Or txtprice.Text = "" Or txtqty.Text = "" Or txttamount.Text = "" Or DateTimePicker1.Text = "" Then
MsgBox("You must have to fill all the Book details.")
Else
Dim strInst As String = "INSERT INTO return(drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
Dim cmd_Insert As New System.Data.SqlClient.SqlCommand(strInst, con)
cmd_Insert.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("New Recored has been Added", MsgBoxStyle.Information)
ProgressBar1.Visible = True
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
End If
Catch ex As Exception
MessageBox.Show("Error while inserting record on table..." & ex.Message, "Error Inserting")
Finally
con.Close()
End Try
End Sub
Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
Try
con.Open()
com.Connection = con
com.CommandText = "UPDATE return SET drug_code ='" & txtdcode.Text & "',c_reg_no='" & txtcreg.Text & "',Sale_price='" & txtprice.Text & "',qty='" & txtqty.Text & "',Tot_amount='" & txttamount.Text & "',date='" & DateTimePicker1.Text & "'"
com.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("Your rocord has been Updated", MsgBoxStyle.Information, "Update Records")
ProgressBar1.Visible = False
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
Catch ex As Exception
MessageBox.Show("Error while updating password on table..." & ex.Message, "Insert Records")
Finally
con.Close()
End Try
End Sub
Private Sub btndelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndelete.Click
Try
con.Open()
com.Connection = con
com.CommandText = "Delete From return Where r_invoice_no=" & txtrinvo.Text
com.ExecuteNonQuery()
ProgressBar1.Visible = True
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 10000
ProgressBar1.Value = 0
Dim I As Integer
For I = ProgressBar1.Minimum To ProgressBar1.Maximum
ProgressBar1.Value = I
Next
MsgBox("Records are deleted with Return Invoice Number..." & txtrinvo.Text, MsgBoxStyle.Information, "Record Deleted.")
ProgressBar1.Visible = False
txtdcode.Text = ""
txtrinvo.Text = ""
txtcreg.Text = ""
txtprice.Text = ""
txtqty.Text = ""
txttamount.Text = ""
DateTimePicker1.Text = ""
Catch ex As InvalidCastException
MessageBox.Show("Error while retrieving records on table..." & ex.Message, "Load Records")
Finally
con.Close()
End Try
End Sub
End Class

Change this line:
Dim strInst As String = "INSERT INTO return(drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
To this:
Dim strInst As String = "INSERT INTO [return](drug_code,c_reg_no,Sale_price,qty,Tot_amount,date,r_invoice_no)VALUES('" & txtdcode.Text & "','" & txtcreg.Text & "','" & txtprice.Text & "','" & txtqty.Text & "','" & txttamount.Text & "','" & DateTimePicker1.Text & "','" & txtrinvo.Text & "')"
Notice the square brackets around the table name. Return is a reserved word in SQL Server, which is causing your error. I would recommend that you change the name of the table. If this is not possible, then you are stuck adding the square brackets every time you use the table.

Related

update and delete is not working vb.net

im having a problem in my codes there's no error showing up and when i press the button nothing happens this is the code im using first one is the update button
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Try
con.Open()
With cmd
.Connection = con
.CommandText = ("Update TBL_EMPLOYEE MiddleName='" & txtMiddleName.Text & "',LastName='" & txtLastName.Text & "', Gender='" & txtGender.Text & "',Age='" & txtupAge.Text & "' ,Address='" & txtupAddress.Text & "', Position='" & txtPos.Text & "',BirthDate='" & Bdate.Text & "' where [FirstName]=#FirstName ")
.Parameters.AddWithValue("FirstName", (txtFirstName.Text))
.ExecuteNonQuery()
.Dispose()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Product Updated", vbInformation, "Information Message")
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error showing up in the code and nothing happening when i pressed the button and same with my delete button
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Try
con.Open()
With cmd
.Connection = cn
.CommandText = "DELETE * from [TBL_EMPLOYEE] where FirstName='" & DataGridView2.CurrentRow.Cells(1).Value.ToString & "' "
.ExecuteNonQuery()
.Dispose()
.Parameters.Clear()
txtFirstName.Text = ""
txtMiddleName.Text = ""
txtLastName.Text = ""
txtGender.Text = ""
txtContactNumber.Text = ""
txtupAge.Text = ""
txtupAddress.Text = ""
txtPos.Text = ""
Bdate.Text = ""
PictureBox2.Image = Nothing
MsgBox("Employee Deleted", MsgBoxStyle.Information)
datagridshow()
End With
Catch ex As Exception
End Try
End Sub
there's no error and nothing happen also here
this is the form load i am using.
Dim str As String
str = ("Server=LOCALHOST\SQLEXPRESS;Database=Payroll;Trusted_Connection=True;")
cn = New SqlConnection(Str)
cn.Open()
Your UPDATE is missing the SET keyword, and your DELETE has a * that shouldn't be there.

Populating combobox in VB from SQL Server database

I have actually done some research on this, and result is shown in my work. But I am still having problems populating the combobox. The form runs fine with no errors, but nothing shows up in the combobox. Can anyone help with this issue? I keep running it over, but I have absolutely no idea where the problem is.
Public Class Form1
Private Sub cboModel_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModel.SelectedIndexChanged
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection error." & vbNewLine &
"The application will now close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
cboModel.BeginUpdate()
cboModel.Items.Clear()
strSelect = "SELECT intAutoID, strMake FROM TAutos"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
cboModel.ValueMember = "intAutoID"
cboModel.DisplayMember = "strMake"
cboModel.DataSource = dt
If cboModel.Items.Count > 0 Then cboModel.SelectedIndex = 0
cboModel.EndUpdate()
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim strSelect As String = ""
Dim strModel As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strSelect = "SELECT strMake, strModel, strYear, strMileage FROM TAutos WHERE intAutoID = " & cboModel.SelectedValue
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
txtMake.Text = dt.Rows(0).Item(0)
txtMileage.Text = dt.Rows(1).Item(1)
txtYear.Text = dt.Rows(2).Item(2)
CloseDatabaseConnection()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim strSelect As String = ""
Dim strMake As String = ""
Dim strMileage As String = ""
Dim strYear As String = ""
Dim intRowsAffected As Integer
Dim cmdUpdate As OleDb.OleDbCommand
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database Connection Error." & vbNewLine &
"The Application Will Now Close.",
Me.Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
strMake = txtMake.Text
strMileage = txtMileage.Text
strYear = txtYear.Text
strSelect = "Update TAutos Set strMake = '" & strMake & "', " & "strMileage = '" & strMileage & "', " & "strYear = '" & strYear & "', " & "Where intAutoID = " & cboModel.SelectedValue
MessageBox.Show(strSelect)
cmdUpdate = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
intRowsAffected = cmdUpdate.ExecuteNonQuery()
If intRowsAffected = 1 Then
MessageBox.Show("Update Failed")
End If
CloseDatabaseConnection()
End Sub
End Class

How to avoid duplicate entries when saving in database in vb.net

I have a button but it can save duplicate entries i don't know how to correctly put a if not exist operator pls help..
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
cn.Open()
i = cmd.ExecuteNonQuery
cn.Close()
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If
You can use NOT EXISTS to prevent duplicate insert:
Dim sql = "INSERT INTO Students(Familyname, Firstname, Middlename, StudentID) " & _
"VALUES(#FamilyName, #Firstname, #Middlename, #StudentID)" & _
"WHERE NOT EXISTS(SELECT 1 FROM Students WHERE StudentId = #StudentID)"
Using cn As New SqlConnection("Your connection string here")
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Parameters.Add("#FamilyName", SqlDbType.VarChar, 50).Value = txtname.Text
cmd.Parameters.Add("#Firstname", SqlDbType.VarChar, 50).Value = txtfname.Text
cmd.Parameters.Add("#Middlename", SqlDbType.VarChar, 50).Value = txtmname.Text
cmd.Parameters.Add("#StudentID", SqlDbType.VarChar, 50).Value = txtid.Text
Dim i = cmd.ExecuteNonQuery
End Using
You should always use parameterized queries to avoid SQL Injection attacks.
NOTE: Please apply appropriate field types.
Try this one :
cn.Open()
Dim intReturn as integer
Dim strSql as string = "Select * from Students where StudentID = #StudentID"
sqlcmd = new sqlcommand(strSql, cn)
With sqlcmd.parameters
.addwithvalue("#StudentID", ctype(txtid.text,string)
End with
intReturn = sqlcmd.ExecuteScalar
If(intReturn > 0)
cmd = New SqlCommand("INSERT INTO Students(Familyname,Firstname,Middlename,StudentID)VALUES('" & txtname.Text & "','" & txtfname.Text & "','" & txtmname.Text & "','" & txtid.Text & "')", cn)
i = cmd.ExecuteNonQuery
If txtname.Text <> "" Then
ElseIf i > 0 Then
MsgBox("Save Sucessfully!", MessageBoxIcon.Information, "Success")
showrecord()
clear()
Else
MsgBox("Save Failed!", MessageBoxIcon.Error, "Error")
End If
Else
MsgBox("Student Already Exist", MessageBoxIcon.Error, "Error")
End If
cn.Close()
And don't forget to make your StudentID field as Unique in your database.

search read sql data to textbox in vb

it show even when i have data inside my database[invalid attempt to read when no data is present]
i was hoping to show details in textbox with txtid.text inserted
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rd As SqlDataReader
Try
con.ConnectionString = "Server=KAVIER;Database=vb;Trusted_Connection=True;"
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader() 'corrected my previous mistake
If rd.HasRows Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
cmd.CommandText = "SELECT * FROM music where mus_id = '" & txtid.Text & "' "
rd = cmd.ExecuteReader()
If rd.read Then
txtartist.Text = rd.Item("customer")
txtid.Text = rd.Item("album")
txtgenre.Text = rd.Item("genre")
hided.Text = rd.Item("music_copies")
txtprice.Text = rd.Item("price")
txttotal.Text = txtprice.Text * txtwalkinquantities.Text
End If
replace rd.HasRows with rd.read

Insert some data from a listview into a ms access database in vb.net

i am trying to insert my listview items into my MS access database.
here is the code:
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewSMS.Click
cn.ConnectionString = newConn
If cn.State = ConnectionState.Closed Then
cn.Open()
For x = 0 To ListView2.Items.Count - 1
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & ListView2.Items(x).SubItems(0).Text & "', '" & ListView1.Items(x).SubItems(1).Text & "','" & ListView1.Items(x).SubItems(2).Text & "','" & ListView1.Items(x).SubItems(3).Text & ")"
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
'End With
Next
End If
cn.Close()
End Sub
my error is:
Value of '0' is not valid for 'index'
my problem is in inserting the values. Please Help me... thanks everyone - Chris
'Try this..
Public newConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Inbox.Accdb;Persist Security Info=False;"
Private Sub btnNewSMS_Click(sender As Object, e As EventArgs) Handles btnNewSMS.Click
For Each x As ListViewItem In ListView2.Items
Dim sqlQuery As String = "INSERT INTO InboxTable (Contact_Name,Contact_Number,DateAndTime,Message) Values ('" & _
x.SubItems(0).Text & "', '" & _
x.SubItems(1).Text & "','" & _
x.SubItems(2).Text & "','" & _
x.SubItems(3).Text & "')"
'Add also the last single qoute before the parenthesis ^_^
'to make sure the query works..
Dim cmd As New OleDbCommand
With cmd
.CommandText = sqlQuery
.Connection = cn
.ExecuteNonQuery()
End With
MsgBox("Messages Saved")
ListView2.Items.Clear()
End With
Next
End Sub
Use this code for more than one form’s
DataTransfer.vb
Public Class DataTransfer
Public Sub ListToData(ByVal strcon As String, ByVal strcmd As String, ByVal listview As ListView)
Dim i As Integer = 0
Dim k As Integer = 0
Dim item As New ListViewItem
Dim con As New System.Data.OleDb.OleDbConnection(strcon)
Dim cmd As New System.Data.OleDb.OleDbCommand(strcmd, con)
Try
MessageBox.Show(listview.Items.Count)
While i < listview.Items.Count
item = New ListViewItem()
item = listview.Items(i).Clone
itemToString(item, strcmd)
con.Open()
cmd.CommandText = strcmd
cmd.ExecuteNonQuery()
MessageBox.Show("saved")
i += 1
End While
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
MessageBox.Show(strcmd)
End Sub
Private Sub itemToString(ByVal item As ListViewItem, ByRef strcmd As String)
Dim k As Integer = 1
strcmd += "VALUES ("
strcmd += "'" & item.Text & "'"
MessageBox.Show("subitems" + item.SubItems.Count.ToString)
While k < item.SubItems.Count
strcmd += ",'" & item.SubItems(k).Text & "'"
k += 1
End While
strcmd += ")"
End Sub
End Class
Form1.vb
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim datatransfer As New DataTransfer
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\User\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\bin\Debug\schoolDB.accdb"
Dim cmd As String = "INSERT INTO Stu_Info (C_ID, ADM_No, S_Name)"
datatransfer.ListToData(con, cmd, ListView1)
End Sub
End Class

Resources