我不知道什么;我的代码错了:请帮助我:(当我运行它时,它给我一个错误。:(没有价值......等等... :(
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim Str As String
Try
Str = "insert into Students values("
Str += txtNick.Text.Trim()
Str += ","
Str += """" & txtFirst.Text.Trim() & """"
Str += ","
Str += """" & txtLast.Text.Trim() & """"
Str += ","
Str += """" & txtAge.Text.Trim() & """"
Str += ","
Str += """" & txtGender.Text.Trim() & """"
Str += ","
Str += """" & txtAddress.Text.Trim() & """"
Str += ","
Str += txtContact.Text.Trim()
Str += ")"
Con.Open()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Dst.Clear()
Dad = New OleDbDataAdapter("SELECT * FROM Students ORDER BY NickName", Con)
Dad.Fill(Dst, "StudsInfo")
MsgBox("Record inserted successfully...")
Con.Close()
Catch ex As Exception
MessageBox.Show("Could Not Insert Record!!!")
MsgBox(ex.Message & " - " & ex.Source)
Con.Close()
End Try
End Sub
答案 0 :(得分:0)
除了对SQL注入持开放态度之外,您的插入设计很糟糕。你应该在它上面使用参数。另外,如果你的表有10列,但你只有6个,那可能会抛出它,除非你明确告诉你要插入哪些列...
由于不知道你要插入的数据库(VFP,dBASE,Excel,Access等),我不知道sql的参数指示器,你将不得不研究它。我会用“?”现在作为每个领域的占位者。
像
这样的东西Str = "insert into Students ( NickName, FirstName, LastName, " &
"Age, Gender, Address, Contact ) " &
"values " &
"( ?parmNickName, ?parmFirstName, ?parmLastName, " &
"?parmAge, ?parmGender, ?parmAddress, ?parmContact )"
Con.Open()
Cmd = New OleDbCommand(Str, Con)
-- Now, add the parameters... Not using VB.Net, the command may be different
-- maybe something like .Parameters.AddWithValue() or similar...
Cmd.Parameters.Add( "parmNickName", txtNick.Text.Trim())
Cmd.Parameters.Add( "parmFirstName", txtFirst.Text.Trim())
Cmd.Parameters.Add( "parmLastName", txtLast.Text.Trim())
Cmd.Parameters.Add( "parmAge", txtAge.Text.Trim())
Cmd.Parameters.Add( "parmGender",txtGender.Text.Trim())
Cmd.Parameters.Add( "parmAddress", txtAddress.Text.Trim())
Cmd.Parameters.Add( "parmContact", txtContact.Text.Trim())
-- NOW, run the query to insert explicit fields and corresponding values
Cmd.ExecuteNonQuery()