How can I Update access database from vb.net app - database

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

Related

Insert data into SQL Server using VBA

I'm trying to create a tool that will import an Excel file data into the SQL Server database. The thing is I get an error
Command Text was not set for the command Object
I guess there's something wrong with my "Do While". I tried first simple insert query no error but it saved in SQL Server as blank.
Private Sub CommandButton1_Click()
Dim SourcePath, DestPath, PMatrixPath, FileExists, x
SourcePath = ThisWorkbook.Worksheets("Config").Cells(2, 2).Value
DestPath = ThisWorkbook.Worksheets("Config").Cells(3, 2).Value
Dim Conn As ADODB.connection
Dim rsSql As New ADODB.Recordset
Dim server_name As String, database_name As String
Dim sqlQuery As String
Dim ShtName As String
Dim rw As Integer
If SourcePath = "" Then
SourcePath = Application.GetOpenFilename _
(Title:="Please choose the Daily APAC file", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If SourcePath = False Then
MsgBox "No Daily RAW data File Selected. Please set the path in Config Tab or select here", vbExclamation, "Sorry!"
Exit Sub
End If
End If
FileExists = Dir(SourcePath)
If FileExists = "" Then
MsgBox "Daily RAW data File doesn't exist in the mentioned path", vbExclamation, "Sorry!"
Exit Sub
End If
With Sheets("Sheet1")
Set Conn = New ADODB.connection
Let server_name = "10.206.88.119\BIWFO"
Let database_name = "TESTDB"
Let UserName = "admin"
Let Password = "pass"
Conn.Open "Provider=SQLOLEDB;Data Source=" + server_name & ";Initial Catalog=TESTDB;" + "Uid=" & UserName + "; Pwd=" & Password + ";"
rw = 2
Do While Not .Range("A" & rw).Value = ""
Sheet1.Range("A2").Value = rw
sqlQuery = "Insert into tbl_MN_Daily_SLA values ('" & .Range("A" & rw).Value & "','" & .Range("B" & rw).Value & "','" & .Range("G" & rw).Value & "','" & .Range("AX" & rw).Value & "','" & .Range("I" & rw).Value & "','" & .Range("AU" & rw).Value & "','" & .Range("AV" & rw).Value & "','" & .Range("J" & rw).Value & "','" & .Range("M" & rw).Value & "','" & CDate(.Range("N" & rw).Value) & "','" & CDate(.Range("S" & rw).Value) & "','" & CDate(.Range("T" & rw).Value) & "','" & .Range("AF" & rw).Value & "','" & .Range("C" & rw).Value & "','" & CDate(.Range("U" & rw).Value) & "','" & .Range("V" & rw).Value & "','" & CDate(.Range("X" & rw).Value) & "','" & CDate(.Range("Y" & rw).Value) & "','" & CDate(.Range("AD" & rw).Value) & "','" & CDate(.Range("AE" & rw).Value) & "','" & .Range("L" & rw).Value & "');"
rw = rw + 1
Loop
Debug.Print sqlQuery
rsSql.CursorLocation = adUseClient
rsSql.Open sqlQuery, Conn, adOpenStatic
Conn.Close
Set Conn = Nothing
End With
End Sub

Update Error in Visual Basic 2010

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.

Cause of "Run-time error code '3061' too few parameters. Expected 1."

The following code causes the error "Run-time error code '3061' too few parameters. Expected 1." but I'm not sure why:
Private Sub cmdAdd_Click()
'to add data to table
CurrentDb.Execute "INSERT INTO student(Name, Age, Sex, Email, Mobile, Course, Name_Of_Kin, Relationship, Email_Of_Kin, Mobile_Of_Kin, School_Fees, Qualification) " & _
"VALUES (" & Me.txtName & " ,'" & Me.DTPAge & "','" & Me.cmbSex & "','" & Me.txtEmail & "','" & Me.txtMobile & "','" & Me.cmbCourse & "','" & Me.txtNOK & "','" & Me.cmbROK & "','" & Me.txtEOK & "','" & Me.txtMOK & "','" & Me.cmbFees & "','" & Me.cmbQual & "')"
frmStudentSub.Form.Requery
End Sub
First, have a look here:
Insert record using a recordset
Then, as it seems you insert the record in a table used by an open form, you can use the RecordsetClone of that form:
Private Sub cmdAdd_Click()
Dim rs As DAO.Recordset
Set rs = frmStudentSub.Form.RecordsetClone
rs.AddNew
rs!Name.Value = Me!txtName.Value
rs!Age.Value = Me!DTPAge.Value
rs!Sex.Value = Me!cmbSex.Value
rs!Email.Value = Me!txtEmail.Value
rs!Mobile.Value = Me!txtMobile.Value
rs!Course.Value = Me!cmbCourse.Value
rs!Name_Of_Kin.Value = Me!txtNOK.Value
rs!Relationship.Value = Me!cmbROK.Value
rs!Email_Of_Kin.Value = Me!txtEOK.Value
rs!Mobile_Of_Kin.Value = Me!txtMOK.Value
rs!School_Fees.Value = Me!cmbFees.Value
rs!Qualification.Value = Me!cmbQual.Value
rs.Update
' Not needed.
' frmStudentSub.Form.Requery
Set rs = Nothing
End Sub

Adding Data to a table with Visual Studio

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

Getting Syntax Error on INSERT INTO command on Visual Basic 2010 to MS ACCESS 2007

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]..........

Resources