sql-server – 如何使用VBNet将数据插入SQL Server?
发布时间:2020-05-23 07:32:55 所属栏目:MsSql 来源:互联网
导读:我是新的vb.net我需要使用vb.net在表中插入数据请任何一个帮助 我试过这个 在这里我尝试了示例代码 我得到这个异常列名或提供的数值与表定义不匹配. 谢谢提前 Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handle
|
我是新的vb.net我需要使用vb.net在表中插入数据请任何一个帮助 我试过这个 在这里我尝试了示例代码 我得到这个异常列名或提供的数值与表定义不匹配. Private Sub btnSave_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles btnSave.Click
Dim strName As String = txtName.Text
Dim strId As String = txtID.Text
Dim strPhone As String = txtPhone.Text
Dim strBranch As String = cmboxBranch.SelectedItem.ToString()
Dim strCourse As String = cmbboxCourse.SelectedItem.ToString()
Dim dblFee As Double = Double.Parse(txtFee.Text)
Dim strCommand As String = "insert into student values('" & strName & "','" & strId & "','" & strPhone & "','" & strBranch & "','" & strCourse & "'," & dblFee & ")"
Dim command As SqlCommand = New SqlCommand(strCommand,connection)
command.CommandType = CommandType.Text
'' MsgBox(strCommand)
connection.Open()
If (command.ExecuteNonQuery().Equals(1)) Then
MsgBox("Information stored in database")
Else
MsgBox("Not stored in database")
End If
End Sub
解决方法这意味着在INSERT语句中的VALUES子句中指定的值的数目不等于表中的总数.如果您只尝试插入选定的列,则必须指定列名.另一个,因为你使用ADO.Net,总是参数化你的查询以避免SQL注入.你现在正在做的是你正在打败sqlCommand的使用. 前 Dim query as String = String.Empty
query &= "INSERT INTO student (colName,colID,colPhone,"
query &= " colBranch,colCourse,coldblFee) "
query &= "VALUES (@colName,@colID,@colPhone,@colBranch,@colCourse,@coldblFee)"
Using conn as New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@colName",strName)
.Parameters.AddWithValue("@colID",strId)
.Parameters.AddWithValue("@colPhone",strPhone)
.Parameters.AddWithValue("@colBranch",strBranch)
.Parameters.AddWithValue("@colCourse",strCourse)
.Parameters.AddWithValue("@coldblFee",dblFee)
End With
Try
conn.open()
comm.ExecuteNonQuery()
Catch(ex as SqlException)
MessageBox.Show(ex.Message.ToString(),"Error Message")
End Try
End Using
End USing
PS:请将查询中指定的列名称更改为表中找到的原始列. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
