I want to add data to my App table in Visual Studio. When I run the program, I fill the information into the text boxes, and when I click the add button, I receive this message from this code:
"Cmd.ExecuteNONQuerry" : An unhandled exception of type
'System.Data.SqlClient.SqlException' occurred in System.Data.dll
When I run "Build Solution" I receive this:
========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
Can somebody please help me.
Imports System.Data.SqlClient
Public Class APP
Dim Con As New SqlConnection
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Con.Open()
Dim Cmd As New SqlCommand(("INSERT INTO App VALUES('" & _
ID.Text & "','" & _
Dat.Text & "','" & _
Inst.Text & "', '" & _
Credent.Text & "', '" & _
AppOwner.Text & "', '" & _
Status.Text & "', '" & _
SerialNr.Text & "', '" & _
MAC.Text & "', '" & _
DellNr.Text & "', '" & _
Model.Text & "', '" & _
Description.Text & _
"', '" & Service.Text & _
"', '" & Indkøbt.Text & "',)"), Con)
Cmd.ExecuteNonQuery()
Con.Close()
MsgBox("Success....", MsgBoxStyle.Information, "SUCCESS")
ID.Clear()
Dat.Clear()
Inst.Clear()
Credent.Clear()
AppOwner.Clear()
Status.Clear()
SerialNr.Clear()
MAC.Clear()
DellNr.Clear()
Model.Clear()
Description.Clear()
Service.Clear()
Indkøbt.Clear()
ID.Focus()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Con.ConnectionString = "Data Source=BYG-A101-MOELKA;Initial Catalog=App;Integrated Security=True"
End Sub
At the first glance:
"', '" & Indkøbt.Text & "',)"), Con)
is wrong, it should be
"', '" & Indkøbt.Text & "')"), Con)
But there is another big Problem: you are not using sqlparameters, so your code will crash if someone enters a "'".
When using an insert like you do, it´s also ... more readable if you also specify the field list to see, if you inserting values in the correct databasefield. But much better change to sqlparameters.
Addition - SQL Parameters (with an update Statement, but the principle should be clear):
sqlStmt = "UPDATE table SET fieldname = #fieldparameter WHERE ..."
Using sqlComm As New SqlCommand(sqlStmt, sqlConn)
sqlComm.Parameters.Add(New SqlParameter("#fieldparameter", yourvalue))
sqlComm.ExecuteNonQuery()
End Using
Related
Im getting a Data type mismatch in criteria expression.
This is an update button Im trying to implement.
Access_Num is the only number(data_type) here.
I'm using MSACCESS2007
Is it a good pracrice to make all data types in the database as text?
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
cn = New OleDbConnection(con)
cn.Open()
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = '" &Integer.Parse(TextBox2.Text) & _
"', [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = '" & Integer.Parse(TextBox2.Text) & "'"
.ExecuteNonQuery()
End With
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
'cn.Close()
'cmd.Dispose()
MsgBox("Successfully Updated")
End Sub
Your problem is that you have string delimiters everywhere. Remove them for all fields that aren't strings:
With cmd
.Connection = cn
.CommandText = "Update [Book] SET [Book_ID] = '" & TextBox1.Text & _
"', [Access_Num] = " & Integer.Parse(TextBox2.Text) & _
", [Title] = '" & TextBox3.Text & _
"', [Author] = '" & TextBox4.Text & _
"', [Publisher] = '" & TextBox5.Text & _
"', [Category] = '" & ComboBox1.Text & _
"', [Contents] = '" & TextBox7.Text & _
"', [Availability] = '" & ComboBox2.Text & "' WHERE [Access_Num] = " & Integer.Parse(TextBox2.Text)
.ExecuteNonQuery()
End With
Note that a better way would be to use parameters for the query, since that also avoids SQL injection.
Is it a good pracrice to make all data types in the database as text?
No, certainly not! That's an awful practice. Data types should represent the data stored in the column, and be the smallest practical type to represent that data.
How can I update my access database in vb.net code I use OleDb connection to the database it's make change in datagridview but not into the database
Public Sub executquery()
Dim commandOleDb As New OleDbCommand(query, con)
commandOleDb.ExecuteNonQuery()
con.Close()
End Sub
--------------------
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs)
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Almaashat.accdb")
Dim query As String
Try
con.Open()
query = "INSERT INTO Techers (File_ID,Name,Workplace,Jop,Appointment,Class,Birthday,End_date,End_class,End_for,Note) VALUES (" & TextBoxFile_ID.Text & " ,'" & TextBoxName.Text & "' ,'" & TextBoxWorkplace.Text & "' ,'" & TextBoxJop.Text & "' ,'" & DateTimePickerAppoiment.Text & "','" & TextBoxClass.Text & "','" & DateTimePickerBirthday.Text & "' ,'" & DateTimePickerEnd_date.Text & "' ,'" & TextBoxEnd_class.Text & "','" & TextBoxEnd_for.Text & "' ,'" & TextBoxNote.Text & "')"
executquery()
con.Close()
MsgBox("Your Data Inserted")
Catch ex As Exception
MsgBox("Your Data Not Inserted")
End Try
TechersDataGridView.DataSource = TechersBindingSource
End Sub
You have the definition of string 'query' and OleDBConnection 'con' only in your private Sub executquery
So to correct that :
Public Sub executquery(query as String, con as OleDBConnection)
Dim commandOleDb As New OleDbCommand(query, con)
con.Open()
commandOleDb.ExecuteNonQuery()
con.Close()
End Sub
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs)
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Almaashat.accdb")
Dim query As String
Try
query = "INSERT INTO Techers (File_ID,Name,Workplace,Jop,Appointment,Class,Birthday,End_date,End_class,End_for,Note) VALUES (" & TextBoxFile_ID.Text & " ,'" & TextBoxName.Text & "' ,'" & TextBoxWorkplace.Text & "' ,'" & TextBoxJop.Text & "' ,'" & DateTimePickerAppoiment.Text & "','" & TextBoxClass.Text & "','" & DateTimePickerBirthday.Text & "' ,'" & DateTimePickerEnd_date.Text & "' ,'" & TextBoxEnd_class.Text & "','" & TextBoxEnd_for.Text & "' ,'" & TextBoxNote.Text & "')"
executquery(query,con)
MsgBox("Your Data Inserted")
Catch ex As Exception
MsgBox("Your Data Not Inserted")
End Try
TechersDataGridView.DataSource = TechersBindingSource
End Sub
Im having a problem of adding records when I click the messagebox and i answered is no then cancel it and add another record but im having a message of connection has not been initialized heres my code thank you.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim reader As SqlDataReader
conn.Open()
Dim bday As String
bday = adyear.Text & "-" & admonth.Text & "-" & adday.Text
If adfirstname.Text.Length < 2 Then
MessageBox.Show("Firstname is too short")
End If
Dim exist As String
exist = "select * from record where firstname='" & adfirstname.Text & "'" & " and lastname='" & adlastname.Text & "';"
cmd = New SqlCommand(exist, conn)
reader = cmd.ExecuteReader
If reader.HasRows = True Then
If MsgBox("THE MEMBER YOU ARE TRYING TO ADD HAS AN SAME FIRSTNAME AND LASTNAME IN THE RECORD DO YOU WISH TO CONTINUE ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
ElseIf adage.Text < 18 Then
If MsgBox("The member is less than 18 years old is this an intern?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim add As String
add = "insert into record(firstname,middlename,lastname,birthday,age,jobposition)" & _
"values(" & _
"'" & adfirstname.Text & "'," & _
"'" & admiddlename.Text & "'," & _
"'" & adlastname.Text & "'," & _
"'" & bday & "'," & _
"'" & adage.Text & "'," & _
"'" & adjobposition.Text & "');"
cmd = New SqlCommand(add, conn)
cmd.ExecuteNonQuery()
MessageBox.Show("Added Complete")
Else
MsgBox("Action is Terminated")
' code for return to adding and stop the messagebox of the connection has not been initialized
End If
End If
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
Well, since it appears the conn is a form level object you would need to call
conn = New SqlConnection(<connection string>)
before you can use it to open the connection. Given that you call
conn.Dispose()
to destroy the conn instance in the Finally block it appears that you do not keep an open connection around for long.
I have 4 tables: Code_Product, Name_Product, Color_Product, Size_Product
And code:
Public Sub ExecuteQuery(query As String)
Dim command As New SqlCommand(query, connection)
command.ExecuteNonQuery()
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
ExecuteQuery(updateQuery)
MessageBox.Show("Data has been changed")
Notes: the code work.
But, the code changes all columns, and I just want to change only one column. How?
replace this line
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' , Color_Product = '" & txtColorProduct.Text & "', Size_Product = '" & txtSizeProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
with this. Pass only that column which you want to update.
Dim updateQuery As String = "UPDATE tbl_Product SET Name_Product = '" & txtNameProduct.Text & "' where Kode_Produk= '" & txtKodeProduk.Text & "'"
I keep getting a syntax error when I run a debug on the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles add.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
'Open Connection if not yet Open
cnn.Open() End If
cmd.Connection = cnn
If Me.sn.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO First_Year(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX,SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother,Occupation_m,School Last Attended,Address School,Middle_Name)" +
"VALUES ('" & Me.sn.Text & "','" & Me.fn.Text & "','" & Me.ln.Text & "' ,'" & Me.Year.Text & "','" & Me.ed.Value & "','" & Me.s.Text & "','" & Me.sy.Text & "','" & Me.cs.Text & "','" & Me.re.Text & "'," & Me.cn.Text & ",'" & Me.bd.Value & "','" & Me.fa.Text & "','" & Me.fo.Text & "','" & Me.ma.Text & "','" & Me.mo.Text & "','" & Me.lad.Text & "','" & Me.ad.Text & "','" & Me.mi.Text & "')"
cmd.ExecuteNonQuery()
Can some please point out to me whats wrong with it?
You have some fields name that contains spaces. To use these fields names you need to enclose them in square brackets
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"...... "
Said that, remember that string concatenations like yours lead to Sql Injection and problem in parsing strings that contains quotes (O'Brien) or decimal numbers or date
Search about Sql Injection and Parameterized queries
A parameterized approach to your query would be
cmd.CommandText = "INSERT INTO First_Year " & _
"(Student_No,Lastname,Firstname,Year_Level,Enroll_Date,SEX, " & _
"SY,CIVIL_STATUS,Religion,Birthdate,TEL_NO,Father,Occupation_F,Mother, " &
"Occupation_m,[School Last Attended],[Address School],Middle_Name) " &
"VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
cmd.Parameters.AddWithValue("#p1", Me.sn.Text)
cmd.Parameters.AddWithValue("#p2", Me.fn.Text)
... and so on for the remainder 16 parameters placeholders
... respecting their position and converting to the appropriate datatype
you need to remove the space here (in your query) :
......School Last Attended,Address School.......
or write it like this :
..........[School Last Attended],[Address School]..........