sql-server - 如何使用 VB Net 将数据插入 SQL Server

标签 sql-server vb.net

我是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 注入(inject)。您现在正在做的是您正在击败 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:请将查询中指定的列名称更改为表中找到的原始列。

关于sql-server - 如何使用 VB Net 将数据插入 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12634516/

相关文章:

SQL - Json 查询

sql-server - SQL Server 中的短 guid/从字符串转换为 uniqueidentifier

sql - 在 SQL Server 中删除记录后重置标识种子

mysql - 如何在Vb.net中的MySQL DateTime列中仅检查月份和年份

javascript - 无法在 UpdatePannel 中获取 DropDownList 控件

vb.net - *微妙* VB函数和Convert.To *函数之间的区别?

加入所需的 SQL Server 查询帮助

sql - 如何在 SELECT FOR XML 查询中选择返回的列名?

.net - 通过 .NET 关闭时 Excel 2007 挂起

c# - 在自定义控件的属性上添加 BindableAttribute 的目的是什么?