从VB.Net到Access数据库的SQL查询

时间:2017-05-25 18:45:05

标签: sql vb.net ms-access

我有一个查询,但是当我尝试它时,会在日期或任何其他变量上给我一些错误。我无法做到对。你能帮我么?这是代码:

 Dim tax As Integer = 10
        Dim APPROVED As Boolean = 1
        Dim admin As String = "admin"
        sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES ('" & TextBox2.Text & "', #" & DateTimePicker1.Value.Date & "#, '" & TextBox1.Text & "', #" & DateTimePicker2.Value.Date & "#, " & TextBox3.Text & ", '" & ComboBox1.SelectedItem.ToString & "', '" & ComboBox2.SelectedItem.ToString & "', " & tax & ", '" & APPROVED & "', '" & admin & "', #" & DateTimePicker1.Value.Date & "#);"

        sqlquery.ExecuteNonQuery()

现在我收到了这个错误:

  

标准表达式中的数据类型不匹配。

想要遵循哪种日期格式?

2 个答案:

答案 0 :(得分:1)

使用参数化查询。

你所拥有的是疯狂的,容易受到SQL注入攻击。参数化查询将解决该问题和格式问题:

Dim tax As Integer = 10
Dim APPROVED As Boolean = 1
Dim admin As String = "admin"
sqlquery.CommandText = "INSERT INTO ACCOUNTS (REFERENCE_NO, ACCT_DATE, ACCT_FROM, ACCT_DUE_DATE, TOTAL, [CURRENCY], AMOUNTS_ARE, TAX, APPROVED, UPDATED_BY, UPDATED_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

sqlquery.Parameters.Add("?", OleDbType.VarWChar, 10).Value = TextBox2.Text
sqlquery.Parameters.Add("?", OleDbType.Date).Value = DateTimePicker1.Value.Date 
'...

sqlquery.ExecuteNonQuery()

答案 1 :(得分:0)

条件表达式中的数据类型不匹配。您正在尝试将错误的数据类型插入数据库。仔细检查数据库中的数据类型。如果是日期,请插入日期,如果是文本,请插入文本。

此外,字符串连接使得查找错误变得更加困难,并且还会让您对SQL注入开放。

以下是使用参数的简单示例:

Using con As New OleDbConnection

            con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; " & _
                                     "Data Source = " & My.Settings.dbpath
            con.Open()

            Dim sql_insert As String = "INSERT INTO Table_Name (Order_ID, Customer_Name) " & _
                                       "VALUES " & _
                                       "(@entry_ref, @customer_name);"

            Dim sql_insert_entry As New OleDbCommand

            con.Open()

            With sql_insert_entry
                .Parameters.AddWithValue("@entry_ref", entry_ref)
                .Parameters.AddWithValue("@customer_name", tb_new_entry_customer_name.Text.Trim())
                .CommandText = sql_insert
                .Connection = con
                .ExecuteNonQuery()
            End With

            con.close()

End Using

正如您所看到的,它可以很容易地跟踪并同时保护您的数据库。