1

我在执行代码时出错。它说“INSERT INTO 语句中的语法错误”。这是我的代码:

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click GridView1.Visible = True

Dim myConn As OleDbConnection      
Dim sqlString, takenby, dest, client, car As String     
Dim recordno As Integer     
Dim dte, exptime As String      
recordno = TextBox4.Text     
dte = TextBox1.Text     
car = ComboBox1.SelectedValue.ToString()     
takenby = ComboBox2.SelectedValue.ToString     
dest = ComboBox3.SelectedValue.ToString     
client = TextBox2.Text     
exptime = TextBox3.Text      
myConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\student\WebSite3\App_Data\Database.mdb;Persist Security Info=False;")      
myConn.Open()     
sqlString = "INSERT INTO DETAILED GISTEC CARS(Record No, Date, Car, Taken By, Destination, Client, Expected Time to Return)VALUES(?recordno, ?dte, ?car, ?takenby, ?dest, ?client, ?exptime);"      
Dim cmd = New OleDbCommand(sqlString, myConn)      
cmd.ExecuteNonQuery()     
myConn.Close() 

End Sub 
4

3 回答 3

1

You should change your query to use question mark placeholders and then add paramters to prevent (amongst other things) sql injection issues.

You also need to add square brackets to your column names if they have spaces in them:

sqlString = "INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (?, ?, ?, ?, ?, ?, ?);"

Dim cmd = New OleDbCommand(sqlString, myConn)
cmd.Parameters.Add(New OleDbParameter("Record No", recordno))
cmd.Parameters.Add(New OleDbParameter("Date", dte))
'etc
'etc
cmd.ExecuteNonQuery()

See this page about OleDbParameters for more information.

于 2012-06-27T12:35:44.673 回答
0

cad 连接方法的替代方法是使用花括号数组占位符。这样的事情应该这样做:

sqlString = String.Format("INSERT INTO [DETAILED GISTEC CARS] ([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6});", recordno, dte, car, takenby, dest, client, exptime)

您还应该在非数字值周围加上单引号,转义任何用户输入的单引号,并为日期/时间列调用 Access CDATE 函数。因此,假设dte是用户输入的数据并且exptime是 Date\Time 列,那么这两个变量可能设置如下:

dte = "'" + TextBox1.Text.Replace("'", "''") + "'"
exptime = "CDATE('" + TextBox3.Text + "')"

等等等等...

于 2012-06-27T12:17:36.823 回答
0

尝试直接在 Access 中执行查询,直到它工作。

从这里看起来

  • VALUES 周围没有空格
  • 您的表名包含空格,因此最好使用 [] 将表名括起来
  • 与某些列名相同。
  • 不确定 vb 中的 ?recordno 语法,所以最好使用 + 运算符

sqlString = "INSERT INTO [DETAILED GISTEC CARS]([Record No], [Date], [Car], [Taken By], [Destination], [Client], [Expected Time to Return]) VALUES (" + recordno + ", " + dte + ", " + car +", " + takenby, " + dest + ", " + client + ", " + exptime + ");"

于 2012-06-27T09:00:22.393 回答