Cannot use the Update Command in visual Studio 2012 - sql

connect()
MD = "update EmpRec set ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "', '" & TextBox4.Text & "', '" & TextBox5.Text & "','" & ComboBox2.Text & "','" & ComboBox3.Text & "','" & Label3.Text & "','" & ComboBox4.Text & "','" & ComboBox5.Text & "','" & TextBox7.Text & "','" & TextBox8.Text & "','" & TextBox9.Text & "','" & Label19.Text & "','" & Label22.Text & "','" & Label25.Text & "','" & TextBox6.Text & "','" & TextBox10.Text & "')"
comm = New OleDbCommand(MD, conn)
comm.ExecuteNonQuery()
MsgBox("Done!", MsgBoxStyle.Information)
grid()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
DataGridView1.Refresh()
TextBox2.Enabled = False
TextBox3.Enabled = False
TextBox4.Enabled = False
TextBox5.Enabled = False
End Sub

This is not the way to write an UPDATE statement.
Try to see what MD looks like. it will probably be something like update EmpRec set ('asdf','zxcv','qwer'...
Where are the column names? Also, as Alex K. wrote in the comment, You really need to change that to a parameterized query.

Related

VB.NET code MS Acess as database and getting error in my code after successful compilation. SYNTAX ERROR in INSERT INTO command

I am getting error in INSERT INTO command.
Code:
Imports System.Data.OleDb
Imports System.IO
Public Class newemployee
Dim read As String
Dim datafile As String
Dim connstring As String
Dim cmd As New OleDbCommand
Public da As New OleDbDataAdapter
Dim str As String
Public ds As New DataSet
Public ds1 As New DataSet
Public ds2 As New DataSet
Dim myconnection As OleDbConnection = New OleDbConnection
Dim er, pho As Integer
Dim Photos1() As Byte
Private Sub newemployee_Load(sender As Object, e As EventArgs) Handles MyBase.Load
read = "provider=microsoft.ace.oledb.12.0;data source="
datafile = "C:\Users\DELL\source\repos\HRIS SYSTEM\loginformdatabase\BLUESTREAM.accdb"
connstring = read & datafile
myconnection.ConnectionString = connstring
ds.Clear()
pho = 0
DateTimePicker1.Value = DateTime.Now
If myconnection.State = ConnectionState.Open Then
myconnection.Close()
End If
myconnection.Open()
er = 0
'cn.Open()
str = "select * from bsemployee"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "bsemployee")
End Sub
'INSERT
Private Sub Save_Click(sender As Object, e As EventArgs) Handles Button3.Click
ds.Clear()
str = "select * from bsemployee"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "bsemployee")
Dim SLNO As Integer
Dim ph As String
SLNO = ds.Tables("bsemployee").Rows.Count + 1
If SLNO >= 0 Then
ph = SLNO
Else
ph = 0
End If
If er = 0 Then
Try
cmd.Connection = myconnection
cmd.CommandText = "INSERT INTO bsemployee(SL NO,EMP SSN,PID,BSPS EMP ID,SIIM ID,FIRST NAME,LAST NAME,NAME,FATHER/HUSBAND NAME,DEPARTMENT,GENDER,DOB,AGE,CURRENT ADDRESS,PERMANENT ADDRESS,EMAIL,COUNTRY,STATE,PHONE NUMBER,PAN,ADHAR NUMER,TE DOJ,
BSPS DOJ,DIVISION,DESIGNATION,TE EMAIL,BSPS EMAIL,BSPS DESIGNATION,COST CENTER,SALARY GRADE,SHIFT,BANK ACCOUNT NO,ACCOUNT CODE,BSPS PF NO,1ST LEVEL SUPERVISOR,2ND LEVEL SUPERVISOR,MANGER,OFFER LETTER ISSUE DATE,NOTICE PERIOD,BOND SIGN,NO OF YEARS,REPORTING,
BG VERIFICATION STATUS,DATE OF RESIGNATION,BASIC SALARY,HOUSE RENT ALLOWANCE,PROVIDENT FUND(Employer distribution),LEAVE TRAVEL ALLOWANCE,MEDICAL ALLOWANCE,SPECIAL ALLOWANCE,STAT BONUS,ESI,MONTHLY GAURENTED CASH,ANNUAL BASIC SALARY,ANNUAL HOUSE RENT ALLOWANCE,
ANNUAL PROVIDENT FUND,ANNUAL LEAVE TRAVEL ALLOWANCE,ANNUAL MEDICAL ALLOWANCE,ANNUAL SPECIAL ALLOWANCE,ANNUAL STAT ALLOWANCE,ANNUAL ESI,ANNUAL GARUNTEED CASH,FOOD COUPON PER ANNUM,GRATIUTY PER ANNUM,INSURANCE PREMIUM PER ANNUM,ANNUAL BONUS,TOTAL COST BENIFIT,GROSS COMPENSATION)
VALUES ('" & TextBox1.Text & "', '" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "','" & TextBox7.Text & "''" & TextBox8.Text & "','" & TextBox9.Text & "','" & TextBox10.Text & "','" & ComboBox1.Text & "','" & DateTimePicker1.Text & "',
'" & TextBox11.Text & "','" & TextBox12.Text & "','" & TextBox13.Text & "','" & TextBox14.Text & "','" & ComboBox2.Text & "','" & TextBox15.Text & "','" & TextBox16.Text & "','" & TextBox17.Text & "','" & TextBox18.Text & "','" & DateTimePicker2.Text & "','" & DateTimePicker3.Text & "','" & TextBox20.Text & "',
'" & TextBox21.Text & "','" & TextBox22.Text & "','" & TextBox23.Text & "','" & TextBox24.Text & "','" & ComboBox3.Text & "','" & TextBox26.Text & "','" & TextBox26.Text & "','" & ComboBox4.Text & "','" & TextBox25.Text & "','" & TextBox27.Text & "','" & ComboBox13.Text & "','" & ComboBox5.Text & "','" & ComboBox6.Text & "','" & ComboBox7.Text & "',
'" & DateTimePicker4.Text & "','" & ComboBox8.Text & "','" & ComboBox9.Text & "','" & ComboBox10.Text & "','" & ComboBox11.Text & "','" & ComboBox12.Text & "','" & DateTimePicker5.Text & "','" & TextBox28.Text & "','" & TextBox29.Text & "','" & TextBox30.Text & "','" & TextBox31.Text & "','" & TextBox32.Text & "','" & TextBox33.Text & "',
'" & TextBox34.Text & "','" & TextBox35.Text & "','" & TextBox36.Text & "','" & TextBox37.Text & "','" & TextBox38.Text & "','" & TextBox39.Text & "','" & TextBox40.Text & "','" & TextBox41.Text & "','" & TextBox42.Text & "','" & TextBox43.Text & "','" & TextBox44.Text & "','" & TextBox45.Text & "','" & TextBox46.Text & "','" & TextBox47.Text & "',
'" & TextBox48.Text & "','" & TextBox49.Text & "','" & TextBox50.Text & "','" & TextBox51.Text & "')"
cmd.ExecuteNonQuery() 'if command is executed'
If pho = 1 Then
'Photo Saving
cmd = New OleDbCommand
cmd.CommandText = " INSERT INTO Photos VALUE (#PhID, #EID, #EName, #EMPImage) "
cmd.Parameters.AddWithValue("#PhID", ph)
cmd.Parameters.AddWithValue("#EID", TextBox1.Text)
cmd.Parameters.AddWithValue("#EName", TextBox8.Text)
Photos1 = File.ReadAllBytes(OpenFileDialog1.FileName)
cmd.Parameters.AddWithValue("#EMPImage", Photos1)
cmd.Connection = myconnection
cmd.ExecuteNonQuery()
End If
'MsgBox("New Class Added.")
Dim result As Integer = MessageBox.Show("New Employee Added. Want To Add Another One.", "Added", MessageBoxButtons.YesNo)
If result = DialogResult.No Then
Me.Close()
ElseIf result = DialogResult.Yes Then
ds.Clear()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
TextBox9.Clear()
TextBox10.Clear()
TextBox11.Clear()
TextBox12.Clear()
TextBox13.Clear()
TextBox14.Clear()
TextBox15.Clear()
TextBox16.Clear()
TextBox17.Clear()
TextBox18.Clear()
TextBox20.Clear()
TextBox21.Clear()
TextBox22.Clear()
TextBox23.Clear()
TextBox24.Clear()
TextBox25.Clear()
TextBox26.Clear()
TextBox27.Clear()
TextBox28.Clear()
TextBox29.Clear()
TextBox30.Clear()
TextBox31.Clear()
TextBox32.Clear()
TextBox33.Clear()
TextBox34.Clear()
TextBox35.Clear()
TextBox36.Clear()
TextBox37.Clear()
TextBox38.Clear()
TextBox39.Clear()
TextBox40.Clear()
TextBox41.Clear()
TextBox42.Clear()
TextBox43.Clear()
TextBox44.Clear()
TextBox45.Clear()
TextBox46.Clear()
TextBox47.Clear()
TextBox48.Clear()
TextBox49.Clear()
TextBox50.Clear()
TextBox51.Clear()
ComboBox1.ResetText()
ComboBox2.ResetText()
ComboBox3.ResetText()
ComboBox4.ResetText()
ComboBox5.ResetText()
ComboBox6.ResetText()
ComboBox7.ResetText()
ComboBox8.ResetText()
ComboBox9.ResetText()
ComboBox9.ResetText()
ComboBox10.ResetText()
ComboBox11.ResetText()
ComboBox12.ResetText()
ComboBox13.ResetText()
DateTimePicker1.ResetText()
DateTimePicker2.ResetText()
DateTimePicker3.ResetText()
DateTimePicker4.ResetText()
DateTimePicker5.ResetText()
str = "select * from bsemployee"
cmd = New OleDbCommand(str, myconnection)
da.SelectCommand = cmd
da.Fill(ds, "bsemployee")
SLNO = ds.Tables("bsemployee").Rows.Count + 1
If SLNO >= 0 Then
TextBox1.Text = SLNO
Else
TextBox1.Text = 0
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
'insert close
End If
'myconnection close
End Sub
The first place I'd look would be for any text with an apostrophe in it - e.g. a surname like O'Rourke - that'll mess up your commandtext. Also, are the date formats compatible with the database date formats - i.e. UK format dates like 25/02/2019 aren't well like by US-centric databases. Similar situation with any numeric formats - might there be currency symbols in the text box?

Number of query values and destination fields are not the same. Error in vb.net

I'm using Microsoft Visual Studio 2010 Express and I'm trying to make a enrollment form using VB.NET. This is my code so far:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cardStr As String
Dim formStr As String
Dim birthStr As String
Dim goodmoralStr As String
If cbcard.Checked Then
cardStr = "OK"
Else
cardStr = ""
End If
If cbform.Checked Then
formStr = "OK"
Else
formStr = ""
End If
If cbbirth.Checked Then
birthStr = "OK"
Else
birthStr = ""
End If
If cbgoodmoral.Checked Then
goodmoralStr = "OK"
Else
goodmoralStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection(conStr)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into tblEnroll(StudID,StudLevel,StudFName,StudMName,StudLName,StudGender,StudBirthday,StudNationality,StudContact,StudPOB,StudCitizenship,StudReligion,MomName,MomContact,MomOccupation,DadName,DadContact,DadOccupation,PrevSchool,Card,F137,BirthCertificate) values ('" & txtID.Text & "','" & lbGrade.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & txtLName.Text & "','" & lbGender.Text & "','" & dtpBirthDate.Text & "','" & txtNationality.Text & "','" & txtStudContact.Text & "','" & txtPOB.Text & "','" & txtCitizen.Text & "','" & txtReligion.Text & "','" & txtMom.Text & "','" & txtMomContact.Text & "','" & txtMomOccupation.Text & "','" & txtDad.Text & "','" & txtDadContact.Text & "','" & txtDadOccupation.Text & "','" & txtPrevSchool.Text & "','" & cardStr & "','" & formStr & "','" & birthStr & "','" & goodmoralStr & "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Student Successfully Enrolled!")`
What could be the solution here?
You have one too many columns in your INSERT statement values. The value goodmoralStr does not have a corresponding column to insert into.
As a slight aside, you really should use parameterised SQL in your code to avoid issues with SQL injection.

The conversion of a varchar data type to a datetime data type throws an out-of-range exception..?

i have taken all date value as date in database but when i give valye 09/11/2014..its accepting but when i give value in -30/10/2014..its giving this kind of error..why..need help...
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'TODO:add data into data base
If ComboBox1.Text <> "" Then
Dim ab As Long
ab = random.Next("10000", "99999")
Dim date1 As Date = Date.ParseExact(TextBox3.Text, "dd/MM/yyyy", Nothing).Date
Dim date2 As Date = Date.ParseExact(TextBox4.Text, "dd/MM/yyyy", Nothing).Date
Dim date3 As Date = Date.ParseExact(TextBox5.Text, "dd/MM/yyyy", Nothing).Date
'Dim date3 As Date = Date.Parse(TextBox5.Text)
Dim date4 As Date = Date.ParseExact(TextBox6.Text, "dd/MM/yyyy", Nothing).Date
If Button1.Enabled = False Then
If TextBox11.Text <> "" And ComboBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "" And TextBox4.Text <> "" Then
TextBox10.Text = ab
cm.Close()
cm.Open()
ComboBox1.Text = Replace(ComboBox1.Text, "'", "''")
TextBox1.Text = Replace(TextBox1.Text, "'", "''")
TextBox7.Text = Replace(TextBox7.Text, "'", "''")
TextBox6.Text = Now.Date.ToString("dd/MM/yyyy")
TextBox8.Text = DateTime.Now.ToString("HH:mm:ss")
cmd.CommandText = "insert into worker(faccno,fname,faddr,famcdue,fjoindate,fdate,fattended,fproblem,fsolution,fstatus,fremark,fassign,findate,fintime,fserviceno,falert)values ('" & TextBox11.Text & "', '" & ComboBox1.Text & "','" & TextBox2.Text & "','" & date1.ToString("dd/MM/yyyy") & "','" & date2.ToString("dd/MM/yyyy") & "','" & date3.ToString("dd/MM/yyyy") & "','" & ComboBox4.Text & "','" & TextBox1.Text & "','" & TextBox7.Text & "','" & ComboBox2.Text & "','" & ComboBox6.Text & "','" & ComboBox5.Text & "','" & date4 & "','" & TextBox8.Text & "','" & TextBox10.Text & "','" & ComboBox3.SelectedIndex & "')"
cmd.ExecuteNonQuery()
MessageBox.Show("Information Insertion sucessfull", "Save")
MessageBox.Show(ab, "your service no is")
Button7.PerformClick()
cm.Close()
Else
MessageBox.Show("enter all values then try to save information", "error")
Exit Sub
End If
ElseIf ComboBox1.Text <> "" Then
cm.Close()
cm.Open()
TextBox1.Text = Replace(TextBox1.Text, "'", "''")
TextBox7.Text = Replace(TextBox7.Text, "'", "''")
TextBox6.Text = Now.Date.ToString("dd/MM/yyyy")
TextBox8.Text = DateTime.Now.ToString("HH:mm:ss")
ComboBox4.Text = Replace(ComboBox4.Text, "'", "''") 'TODO:this code replaces single quotes to store in data base
cmd.CommandText = "update worker set faccno= '" & TextBox11.Text & "', fname='" & ComboBox1.Text & "',faddr='" & TextBox2.Text & "',famcdue='" & date1 & "',fjoindate='" & date2 & "',fdate='" & date3 & "',fattended='" & ComboBox4.Text & "',fproblem='" & TextBox1.Text & "',fsolution= '" & TextBox7.Text & "',fstatus='" & ComboBox2.Text & "',fremark='" & ComboBox6.Text & "',fassign= '" & ComboBox5.Text & "',findate='" & date4 & "',fintime='" & TextBox8.Text & "',fserviceno='" & TextBox10.Text & "',falert='" & ComboBox3.SelectedIndex & "' where fserviceno='" & TextBox10.Text & "'"
cmd.ExecuteNonQuery()
MessageBox.Show(" Information Updation sucessfull", "Save")
Button7.PerformClick()
cm.Close()
End If
Else
MessageBox.Show("enter all values then try to save information", "error")
Exit Sub
End If
End Sub
Before addressing your actual problem, I note that you're using string-concatenation to form SQL statements (DO NOT DO THIS EVER - use typed parameters instead!)
With respect to your posted problem: There are multiple possible causes, but the most probable cause is this line here:
TextBox6.Text = Now.Date.ToString("dd/MM/yyyy")
...you're converting the date to dd/MM/yyyy format but your SQL server might expect slash-separated dates to be in the format MM/dd/yyyy (the default 1033 format - blame the Americans), in which case a month component of 30 doesn't make sense, hence the failure.
If you used parameters then you wouldn't have this problem, as the actual date value (rather than a string representation of it) is passed into the database client library which can then correctly serialize it for you in a way that will always work.

Query error "syntax error in INSERT into"

It seems that I always have the error "syntax error in INSERT into". Can you tell me why?
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Bro_Proj.accdb"
conn.Open()
Dim sql As String = "INSERT INTO Order(Stud_ID, BookName, Quantity, sale, DateOfOrder, TimeOfOrder) VALUES ('" & TextBox1.Text & "', '" & ComboBox3.Text & "', '" & NumericUpDown1.Value & "','" & TextBox10.Text & "',' " & TextBox8.Text & "','" & TextBox9.Text & "') ;"
Dim sqlc As New System.Data.OleDb.OleDbCommand(sql, conn)
sqlc.ExecuteNonQuery()
conn.Close()
The Quantity Data type is Integer so you must remove the simple quote in the qyantity argument, the true code will be as below:
Dim sql As String = "INSERT INTO Order(Stud_ID, BookName, Quantity, sale, DateOfOrder, TimeOfOrder)
VALUES ('" & TextBox1.Text & "', '" & ComboBox3.Text & "', " & NumericUpDown1.Value & ",'" & TextBox10.Text & "',' " & TextBox8.Text & "','" & TextBox9.Text & "')"

Syntax error in INSERT INTO Statement in vb.net

I am getting and syntax error in insert into statement. IF statement is working just fine just getting this error when it's trying to save the information
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
If txt12Per.Text >= TextBox12.Text And txtGPer.Text >= TextBox11.Text And TextBox1.Text >= TextBox10.Text Then
Try
'Dim da As OleDb.OleDbDataAdapter
Dim dbprovider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Taher\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsApplication1\Database1.accdb;Persist Security Info=False;"
Me.con = New OleDb.OleDbConnection()
con.ConnectionString = dbprovider
con.Open()
Dim sqlquery As String = "INSERT INTO MCAscheduled (URno,SName,hsc,gper,pgper,pstatus,cname,hrname,position,hscinter,ginter,pginter,comments)" + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "'," & CInt(txt12Per.Text) & "," & CInt(txtGPer.Text) & "," & CInt(TextBox1.Text) & ",'" & ComboBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & ComboBox4.Text & "'," & CInt(TextBox12.Text) & "," & CInt(TextBox11.Text) & "," & CInt(TextBox10.Text) & ",'" & TextBox9.Text & "');"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
With sqlcommand
.CommandText = sqlquery
.Connection = con
.ExecuteNonQuery()
con.Close()
txtUrn.Text = ""
txt12Per.Text = ""
txtGPer.Text = ""
txtName.Text = ""
cmbNameofGCourse.Text = ""
End With
MsgBox("Record Added")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Else
MsgBox("Student Not eligible for the requested company")
End If
End Sub
Can somebody help me with this....
You are trying to insert into 13 columns but provide only 11 values!
You have 13 fields to insert values in, but only 11 values.
Use brackets and it will work fine.
Dim sqlquery As String = "INSERT INTO MCAscheduled **([URno],[SName],[hsc],[gper],[pgper],[pstatus],[cname],[hrname],[position],[hscinter],[ginter],[pginter],[comments])"** + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "'," & CInt(txt12Per.Text) & "," & CInt(txtGPer.Text) & "," & CInt(TextBox1.Text) & ",'" & ComboBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & ComboBox4.Text & "'," & CInt(TextBox12.Text) & "," & CInt(TextBox11.Text) & "," & CInt(TextBox10.Text) & ",'" & TextBox9.Text & "');"
had to change the position field to something else don't know why but it worked
Dim sqlquery As String = "INSERT INTO MCAscheduled (URno,sname,hsc,gper,pgper,pstatus,cname,hrname,hscinter,ginter,pginter,comments,post,course,pcourse)" + "VALUES (" & CInt(txtUrn.Text) & ",'" & txtName.Text & "'," & CInt(txt12Per.Text) & "," & CInt(txtGPer.Text) & "," & CInt(TextBox1.Text) & ",'" & ComboBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "'," & CInt(TextBox12.Text) & "," & CInt(TextBox11.Text) & "," & CInt(TextBox10.Text) & ",'" & TextBox9.Text & "','" & ComboBox1.Text & "','" & cmbNameofGCourse.Text & "','" & TextBox5.Text & "');"