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

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...