【问题标题】:How can I Insert data into SQL Server using VBNet如何使用 VB Net 将数据插入 SQL Server
【发布时间】:2012-09-20 00:20:39
【问题描述】:

我是vb.net的新手,我需要使用vb.net在表格中插入数据,请任何人帮忙

我试过了

这里我尝试了示例代码

我得到了这个异常Column name or number of supplied values does not match table definition. 谢谢提前

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

【问题讨论】:

  • 您应该向我们展示表定义。也许您忘记了使用自动增量创建 pk 列 IDENTITY。顺便说一句,您可以使用 SQL 注入。你应该使用SqlParameters。
  • 我的表defn 是student(SName,SID,SPhone,SBranch,SCourse,SFee) 都属于varchar 类型除了fee (fee is real type)
  • @rangasathish - 这不是表定义。最简单的方法是使用 SQL Server Management Studio (SSMS) 访问表。右键单击它,选择“脚本表 -> 作为创建 -> 到剪贴板”。然后编辑您的问题并粘贴到结果中。它将向我们展示表的数据类型、任何约束等。

标签: sql-server vb.net


【解决方案1】:

这意味着在INSERT 语句的VALUES 子句中指定的值的数量不等于表中的总列数。如果您只尝试在选定的列上插入,则必须指定列名。

另一个,因为您使用的是ADO.Net,所以总是参数化您的查询以避免SQL Injection。你现在正在做的是击败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:请将查询中指定的列名更改为在您的表中找到的原始列。

【讨论】:

  • 旁注:conn.Close 是多余的,因为无论如何你都在使用using-statement。
  • @TimSchmelter 感谢您的提醒 :) 但我曾经这样做过。无论如何,我只是更新我的答案。
  • 如果可以的话,我会投票支持参数化查询的推广
  • @JohnWoo:无论如何,+1 因为使用参数、使用语句、错误处理和一个可能的错误原因。
  • 您可能还想提到'Error here' 应该替换为适当的error handling(例如日志记录)。永远不要swallow exceptions。
【解决方案2】:
Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

【讨论】:

  • ⚠️ 不要使用。不安全/糟糕的 SQL 编码实践。
【解决方案3】:
Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

【讨论】:

  • 请考虑为您的代码添加更多细节和解释。
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
相关资源
最近更新 更多