问题
I have checked most of the forums on this site but I didn't get my Solution. My problem is Inserting data from vb.net to MS Access but I am not able to do. Its not showing any error but also its not inserting values in my table. I am using very simple code:
Imports System.Data.OleDb
Public Class Add_LEads
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Private Sub Add_LEads_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\IndGlobalDB.accdb;Persist Security Info=True;Jet OLEDB:Database Password=admin")
lblDate.Text = Format(Date.Now, "yyyy/MM/dd")
conn.Open()
Dim sql As String
Dim a As Integer
sql = "select S_No from Leadss"
cmd = New OleDbCommand(sql, conn)
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
While dr.Read
a = dr(0)
End While
lblNo.Text = a + 1
conn.Close()
End Sub
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO Leadss(S_No,Contact_Person,Mobile_No,Email_Id,Description,First_Follow_Up,Remarks,L_Date,Alternate_no)VALUES('" & lblNo.Text & "','" & txtName.Text & "','" & txtMobile.Text & "','" & txtEmail.Text & "','" & txtWebDescr.Text & "','" & txtFollowUp.Text & "','" & txtRemarks.Text & "','" & lblDate.Text & "','" & txtAlternate.Text & "')"
cmd.ExecuteNonQuery()
conn.Close()
MsgBox("Saved!!!", vbOK)
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
Welcome.Show()
End Sub
End Class
回答1:
You should use parametrized query to avoid Sql Injection Attacks and let the JET engine parse your string parameters for invalid characters.
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnSave.Click
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO Leadss(S_No,Contact_Person,Mobile_No,Email_Id," & _
"Description,First_Follow_Up,Remarks,L_Date,Alternate_no) VALUES " & _
"(?, ?, ?, ?, ?, ?, ?, ?, ?)"
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("@p1", lblNo.Text)
cmd.Parameters.AddWithValue("@p2", txtName.Text)
cmd.Parameters.AddWithValue("@p3", txtMobile.Text)
cmd.Parameters.AddWithValue("@p4", txtEmail.Text)
cmd.Parameters.AddWithValue("@p5", txtWebDescr.Text)
cmd.Parameters.AddWithValue("@p6", txtFollowUp.Text)
cmd.Parameters.AddWithValue("@p7", txtRemarks.Text)
cmd.Parameters.AddWithValue("@p8", lblDate.Text)
cmd.Parameters.AddWithValue("@p9", txtAlternate.Text)
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Said that, this works only if your field types are of text type and not numeric or datetime or boolean, in that case your should convert the input text in the appropriate type using Convert.ToXXXXX methods.
(The example below assumes that your inputs contains valid numbers and dates)
....
cmd.Parameters.AddWithValue("@p3", Convert.ToInt32(txtMobile.Text))
.....
cmd.Parameters.AddWithValue("@p8", Convert.ToDateTime(lblDate.Text))
cmd.Parameters.AddWithValue("@p9", Convert.ToInt32(txtAlternate.Text))
Another wrong approach is to keep global variables for reuse like your OleDbConnection, OleDbCommand. This prevent the runtime to dispose these objects when not used. Instead you should follow this approach
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data " +
"Source=|DataDirectory|\IndGlobalDB.accdb;" +
"Persist Security Info=True;Jet OLEDB:Database Password=admin")
Using cmd = New OleDbCommand()
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO ................"
cmd.Parameters.AddWithValue("@p1", lblNo.Text)
..........
End Using
End Using
回答2:
Here's a simple example for the use of SqlParameter and the try/catch block:
Dim connection As SqlConnection = As New SqlConnection("YourDbConnection")
Dim command As SqlCommand = connection.CreateCommand()
Try
connection.Open()
command.CommandText = "INSERT INTO Leadss(S_No) VALUES (@S_No)"
command.Parameters.Add("@S_No", SqlDbType.Text)
command.Parameters["@FirstName"].Value = lblNo.Text
command.ExecuteNonQuery()
Catch Ex As SqlException
'Process the exception
Finally
connection.Close()
End Try
回答3:
Use Backticks (`
) in your FROM
Statement. It should be FROM(`Field1`,`Field2`,...etc) Values('value1', 'value2')
.
回答4:
write this coding according to your database name, table name, field names in save button's click event...
Using conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\user\Documents\Visual Studio 2008\Projects\demo for db in access\demo for db in access\DatabaseforDemo.accdb'")
Using cmd = New OleDbCommand()
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO demo1(Name) VALUES('" & TextBox1.Text & "')"
'cmd.Parameters.AddWithValue("@p1", lblNo.Text)
cmd.ExecuteNonQuery()
MsgBox("saved..")
conn.Close()
End Using
End Using
good luck... hope so it'll help you...!
回答5:
In your question you said:
Its not showing any error but also its not inserting values in my table
Try to use Commit.
A COMMIT statement in SQL ends a transaction within a relational database management system (RDBMS) and makes all changes visible to other users. The general format is to issue a BEGIN WORK statement, one or more SQL statements, and then the COMMIT statement. Alternatively, a ROLLBACK statement can be issued, which undoes all the work performed since BEGIN WORK was issued. A COMMIT statement will also release any existing savepoints that may be in use. In terms of transactions, the opposite of commit is to discard the tentative changes of a transaction, a rollback.
quoted here: Commit (data management)
Try
'Open Connection...
'Insert Statement....
'Notification / Msgbox to confirm successful transaction
Catch ex As Exception
'RollBack Transaction...
'Error Management...
Finally
'Commit...
'Close DB Connection....
End Try
Microsoft Documentation: OleDbTransaction.Commit Method ()
but remember: you should use transactions only if you are inserting/updating multiple SQL statements which then make sense for the rollback.
Here is an Example in Adding transaction management into a form using MS Access 2010
来源:https://stackoverflow.com/questions/12954039/inserting-and-updating-values-in-ms-access-using-vb-net