我无法从VB.NET连接到SQL Server

时间:2018-06-01 01:22:55

标签: .net sql-server vb.net

我无法使用vb.net连接到SQL Server。

这是我的代码:

Imports system.data.sqlclient

PUBLIC CLASS customer_typer

    Dim connectionstring as string = "data source = wisdon; initial catalog = stock_management; user id = sa; password = managerz "

    Dim mycommand as new sqlcommand
    Dim myconnection = new sqlcomma d (connectionstring)

    PRIVATE SUB CUSTOMER_BT
        dim sqlstr as string
        Sqlstr = " insert into customer_type(customer_type) values"  & _
            "(' " & customertyper_txt.text & " ')"
        Mycommand = new sqlclient.sqlcommand (sqlstr, myconnection)

        Mycommand.executeNonQuery ()

        Myconnection.close

Customer_type是我正在编写代码的按钮

Customertype_txt是文本框

1 个答案:

答案 0 :(得分:1)

您忘了打开连接。您还尝试将连接声明为命令。我已添加参数来防止sql注入,如@marc_s所示。 Using ... End Using语句确保即使出现错误也会关闭和处理对象。

Using myconnection = New SqlConnection(connectionstring)
            Dim Sqlstr As String = " insert into customer_type(customer_type) values(@CustomerType);"
            Using mycommand As New SqlClient.SqlCommand(Sqlstr, myconnection)
                mycommand.Parameters.Add("@CustomerType", SqlDbType.VarChar).Value = customertyper_txt.text
                myconnection.Open()
                mycommand.ExecuteNonQuery()
                myconnection.Close()
            End Using
End Using