sql-server – 如何使用VBNet将数据插入SQL Server?

前端之家收集整理的这篇文章主要介绍了sql-server – 如何使用VBNet将数据插入SQL Server?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是新的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:请将查询中指定的列名称更改为表中找到的原始列.

猜你在找的MsSQL相关文章