0

这是我不能在我的代码中使用插入查询的事情,我的代码中有一个错误SqlCommand,说ExecuteNonQuery()与值不匹配等等等等

这是我的代码

Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;")

Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia]  Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')"

con.Open()
cmd.ExecuteNonQuery()
con.Close()

问题是cmd.CommandText任何人都可以帮助我吗?

4

1 回答 1

4

You need to rewrite your query to use a parameterized query. This would avoid parsing problems if your textboxes contains single quotes and, most important, would remove any possibility of Sql Injection.

So you code could look like this

Dim cmdText = "Insert Into [Finals].[dbo].[Nokia]  Values (@unit, @price,@stack," & _ 
              "@processor,@size,@ram,@internal,@lastvalue"
Using con As New SqlConnection(......)
Using cmd As New SqlCommand(cmdText, con)
   con.Open()
   cmd.Parameters.AddWithValue("@unit",Unit.Text )
   cmd.Parameters.AddWithValue("@price",Price.Text)
   cmd.Parameters.AddWithValue("@stack",Stack.Text)
   cmd.Parameters.AddWithValue("@processor", Processor.Text)
   cmd.Parameters.AddWithValue("@size",Size.Text)
   cmd.Parameters.AddWithValue("@ram", RAM.Text)
   cmd.Parameters.AddWithValue("@internal",Internal.Text)
   cmd.Parameters.AddWithValue("@lastvalue", ComboBox1.Text)
   cmd.ExecuteNonQuery()
End Using
End Using

Said that, be aware of two more problems:

You don't specify a column list before the VALUES statement. This means that you need to pass the exact number of parameters for every column present in your table named Nokia AND in the EXACT ORDER of the underlying columns. If you forget one parameter you will receive an exception and if you swap the order of the parameters you end writing your data in the wrong column (with an exception waiting for you if the datatype doesn't match).

The second problem concerns the datatype of every parameter passed to the query. In your case you use the Text property of the textboxes and this means that you are passing a string for every column in the datatable. Of course, if a column expects a numeric value you get a mismatch error.

For example the @price parameter could be used to update a decimal column in the datatable and thus you need to convert the parameter from string to decimal before adding it using the AddWithValue method

 cmd.Parameters.AddWithValue("@price",Convert.ToDecimal(Price.Text))
于 2013-10-18T14:33:21.913 回答