微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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:请将查询中指定的列名称更改为表中找到的原始列.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐