在vb.net中将数据插入SQL Server

时间:2018-03-19 18:25:17

标签: sql-server vb.net

我正在尝试将数据添加到SQL Server数据库中,但它无法正常工作。

以下是我正在使用的代码:

Private Sub Button12_Click(sender As Object, e As EventArgs) Handles save.Click
    Try
        conn.Open()
        cmd.Connection = conn
        cmd.CommandText = "insert into prod (poductID, Name, Type, Kg/Units, Length, Width Hight, Area/m2) values('" & id.Text & "','" & pdt.Text & "','" & type.Text & "','" & kg.Text & "','" & lg.Text & "','" & wdt.Text & "', '" & ht.Text & "', '" & area.Text & "' )"

        cmd.ExecuteNonQuery()

    Catch ex As Exception
        MessageBox.Show("Error while inserting data into database...." & ex.Message, "insert data")
    Finally
        conn.Close()
    End Try
End Sub

Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click

    id.Clear()
    type.Clear()
    eid.Clear()
    kg.Clear()
    lg.Clear()
    wdt.Clear()
    ht.Clear()
    area.Clear()
End Sub

以下是数据库的连接代码,它正在运行:

Imports System.Data
Imports System.Data.SqlClient

Public Class Form1
    Dim conn As New SqlConnection("Data Source=JUMAH;Initial Catalog=production;Integrated Security=False;User ID=jumah;Password=256jumah;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False ")
    Dim cmd As New SqlCommand
    Dim dr As SqlDataReader

3 个答案:

答案 0 :(得分:0)

要做的第一件事是重命名表格中的字段,例如删除/和空格。确保字段名称不是SQL-Server中的保留字。

提示,在命名字段时,例如Kg单位可以更改为Kg_Units,然后当需要在控件(如DataGridView)中显示时,将Kg_Units指定为列的数据源,然后将列标题设置为Kg / Units。

确保主键是自动增量。

在回复之前听取评论!!!

我建议使用一个类进行数据操作,数据操作不应该是你的形式,而是可以从数据类中调用。

以下是(许多路径之一)用于添加新记录的蓝图。不要简单地复制此代码,而是首先修改数据库表,如上所述。

SQL语句以XML文字格式完成,这意味着零字符串连接,因此我们可以清楚地了解该语句。

Imports System.Data.SqlClient

Public Class DataOperations
    ''' <summary>
    ''' Pass in values (you may need to adjust the types for
    ''' the INSERT, last parameter is by ref, create a integer
    ''' variable in the calling method, pass it in here. If
    ''' the operation is successful the integer will have the
    ''' new primary key.
    ''' </summary>
    ''' <param name="pName"></param>
    ''' <param name="pType"></param>
    ''' <param name="pUnits"></param>
    ''' <param name="pLength"></param>
    ''' <param name="pWidthHeight"></param>
    ''' <param name="pArea"></param>
    ''' <param name="pNewIdentifier"></param>
    ''' <returns></returns>
    Public Function AddRecord(
        ByVal pName As String,
        ByVal pType As String,
        ByVal pUnits As Integer,
        ByVal pLength As Integer,
        ByVal pWidthHeight As String,
        ByVal pArea As Integer,
        pNewIdentifier As Integer) As Boolean

        Using cn As New SqlConnection With {.ConnectionString = "TODO"}
            Using cmd As New SqlCommand With {.Connection = cn}
                cmd.CommandText =
                    <SQL>
                        INSERT INTO [prod] 
                        (
                            [Name], 
                            [Type], 
                            [Kg/Units], 
                            [Length], 
                            [Width Hight], 
                            [Area/m2]
                        ) 
                        VALUES 
                        (
                            @Name, 
                            @Type, 
                            @Units, 
                            @Length, 
                            @WidthHeight, 
                            @Area
                        ); 
                        SELECT CAST(scope_identity() AS int);
                    </SQL>.Value

                cmd.Parameters.AddWithValue("@Name", pName)
                cmd.Parameters.AddWithValue("@Type", pType)
                cmd.Parameters.AddWithValue("@Units", pUnits)
                cmd.Parameters.AddWithValue("@Length", pLength)
                cmd.Parameters.AddWithValue("@WidthHeight", pWidthHeight)
                cmd.Parameters.AddWithValue("@Area", pArea)

                cn.Open()

                Try
                    pNewIdentifier = CInt(cmd.ExecuteScalar)

                    Return True

                Catch ex As Exception

                    Return False

                End Try
            End Using
        End Using
    End Function
End Class

答案 1 :(得分:0)

您可以尝试以下代码。请确保您的连接字符串正确。我已将连接字符串,表和列名称用于测试目的。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim query As String = String.Empty
        query &= "INSERT INTO TestType (TestTypeName, Description, Amount) "
        query &= "VALUES (@TestTypeName,@Description, @Amount)"

        Using conn As New SqlConnection("data source=DESKTOP-M8O33JL\SQLEXPRESS2014;initial catalog=MediAid;persist security info=True;user id=sa;password=sa12345")
            Using comm As New SqlCommand()
                With comm
                    .Connection = conn
                    .CommandType = CommandType.Text
                    .CommandText = query
                    .Parameters.AddWithValue("@TestTypeName", "Test Name")
                    .Parameters.AddWithValue("@Description", "Test Description")
                    .Parameters.AddWithValue("@Amount",300)
                End With
                Try
                    conn.Open()
                    comm.ExecuteNonQuery()
                Catch ex As SqlException
                    MessageBox.Show(ex.Message.ToString(), "Error Message")
                End Try
            End Using
        End Using
    End Sub

如果你有进一步的问题。随时写评论部分。感谢。

答案 2 :(得分:0)

这不是最好的做法,但您可能想尝试一下。 您可能还想了解有关VB.net中的接口配置和SQL语法的更多信息。

形式:

    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles save.Click
    Try
        Dim cmd As New SqlCommand("your insert query string")
        Dim dbclass As New DatabaseClass
        If dbclass.fncInsert(cmd) Then
            msgbox("successfull")
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

数据库类:

    Public Function fncInsert(ByVal cmd As SqlCommand) As Boolean
    fncInsert = Nothing
    Try
        Using m_sqlCon As New SqlConnection("Your connection string")
            Using adpr As New SqlDataAdapter
                cmd.Connection = m_sqlCon
                adpr.InsertCommand = cmd
                fncInsert = If(adpr.InsertCommand.ExecuteNonQuery() > 0, True, False)
            End Using
        End Using
    Catch ex As Exception
        msgbox(ex)
    End Try
End Function
抱歉我的英语不好。