我做了一个测验,该测验应该将学生姓名和分数保存到访问数据库中的正确表中。有3个表。我试图连接和编码数据库,但我不断收到以下错误消息:
未处理的类型' System.InvalidCastException'发生在Microsoft.VisualBasic.dll中 附加信息:从字符串" INSERT INTO Class1转换([StudentScor"键入' Double'无效。
我试图找到这个错误的解决方案,但是我并不完全理解。这是我的保存按钮代码,它应该将名称和分数保存到正确的表中:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
StudentClass = cbSelectClass.SelectedItem
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
DataFile = IO.Path.Combine(Application.StartupPath, "StudentScores.accdb")
ConnString = Provider & DataFile
If StudentClass = "Class1" Then
Strng = "INSERT INTO Class1 ([StudentScores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
ElseIf StudentClass = "Class2" Then
Strng = "INSERT INTO Class2 ([Student Scores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
ElseIf StudentClass = "Class3" Then
Strng = "INSERT INTO Class3([StudentScores], [Score]) Values('" + CType(txtName.Text, String) + CType(Score, Integer)
End If
MyConnection.ConnectionString = ConnString
Dim cmd As OleDbCommand = New OleDbCommand(Strng, MyConnection)
MyConnection.Open()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
txtName.Clear()
Catch ex As Exception
MsgBox(ex.Message)
cmd.Dispose()
MyConnection.Close()
End Try
Me.Close()
End Sub
答案 0 :(得分:2)
你有很多不必要的CType继续进行。 Textbox.Text已经是string类型。您不希望将Score转换为Integer,因为您正在连接到字符串。此外,习惯了String.Format函数,因为它将帮助您编写可读性并帮助您找到错误命名的DB列名称。不要害怕空白区域的可读性:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Const SQL_INSERT As String = "INSERT INTO {0} (StudentScores, Scores) VALUES ('{1}', {2})"
Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
DataFile = IO.Path.Combine(Application.StartupPath, "StudentScores.accdb")
ConnString = Provider & DataFile
Dim sql As String = String.Format(SQL_INSERT, cbSelectClass.SelectedItem, txtName.Text.Trim, Score.ToString)
MyConnection.ConnectionString = ConnString
Dim cmd As OleDbCommand = New OleDbCommand(sql, MyConnection)
MyConnection.Open()
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
MyConnection.Close()
txtName.Clear()
Catch ex As Exception
MsgBox(ex.Message)
cmd.Dispose()
MyConnection.Close()
End Try
Me.Close()
End Sub
现在,您必须查看SQL注入以更正它,并且您应该使用Using语句来初始化Connection和Command对象。