我是VB的新手,我正在创建一个程序来连接ms访问,但是当我运行程序时它会得到
Insert into语句中的语法错误,OleDbExpection未处理
这是我的代码:
Public Class Form2
Dim cnn As New OleDb.OleDbConnection
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtdate.Value = DateTime.Now
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=C:\Users\John\Documents\db.mdb"
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim cmd As New OleDb.OleDbCommand
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO sr(names,add,tel,dates,prob,serv,model,snm,acc,sna,remark)" & _
"VALUES ('" & Me.txtname.Text & "','" & Me.txtadd.Text & "','" & Me.txttel.Text & "', '" & _
Me.txtdate.Text & "','" & Me.txtpro.Text & "','" & Me.txtser.Text & "','" & Me.txtmod.Text & "', '" & _
Me.txtsnm.Text & "','" & Me.txtacc.Text & "','" & Me.txtsna.Text & "','" & Me.txtrem.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
End Sub
End Class
我的代码有什么问题吗?
答案 0 :(得分:4)
使用SQL Injection
使您的代码更具可读性和免疫力,请使用以下
Using
声明片段,
Dim comText As String = "INSERT INTO sr(names,add,tel,dates,prob,serv,model,snm,acc,sna,remark) " & _
"VALUES (@names,@add,@tel,@dates,@prob,@serv,@model,@snm,@acc,@sna,@remark)"
Dim connString As String = "ConnectionString Here"
Using conn As New OleDbConnection(connString)
Using comm As New OleDbCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = comText
.Parameters.AddWithValue("@names" , txtname.Text)
.Parameters.AddWithValue("@add" , txtadd.Text)
.Parameters.AddWithValue("@tel" , txttel.Text)
.Parameters.AddWithValue("@dates" , txtdate.Text)
.Parameters.AddWithValue("@prob" , txtpro.Text)
.Parameters.AddWithValue("@serv" , txtser.Text)
.Parameters.AddWithValue("@model" , txtmod.Text)
.Parameters.AddWithValue("@snm" , txtsnm.Text)
.Parameters.AddWithValue("@acc" , txtacc.Text)
.Parameters.AddWithValue("@sna" , txtsna.Text)
.Parameters.AddWithValue("@remark" , txtrem.Text)
End With
Try
conn.Open()
comm.ExecuteNonQuery
Catch ex As OleDbException
' do something with the error
' don't hide it!
End Try
End Using
End Using
SOURCES
答案 1 :(得分:1)
你的VB代码很好(这并不像其他人提到的那样理想,但它并不是错误的。)
语法错误(通常为OleDbExpection
)表示您生成的SQL字符串对您的数据库无效。要调试它,您需要在调用cmd.ExecuteNonQuery()
之前查看生成的SQL字符串,并确保它是有效的SQL。
由于您的某个输入文本框中包含无效数据,因此很可能是 。您可以使用简单的If ... Then
语句
If Not String.IsNullOrEmpty(Me.txtdata.Text) Then
'Add the txtdata parameter
End If