2

我正在尝试将供应商数据插入到我在 VB.NET 中构建的 SQL 数据库中。

这是我正在使用的代码:

Dim myconnect As New SqlClient.SqlConnection
        myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB\InvDB.mdf;Integrated Security=True;User Instance=True"


        Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
        mycommand.Connection = myconnect
        mycommand.CommandText = "INSERT INTO Supplier (SupplierID, Name, Email,Phone,Address,City) VALUES (@SID, @Name, @Email, @Phone, @Address, @City)"
        myconnect.Open()

        Try
            mycommand.Parameters.Add("@SID", SqlDbType.Int).Value = SIDTextBox.Text
            mycommand.Parameters.Add("@Name", SqlDbType.NVarChar).Value = NameTextBox.Text
            mycommand.Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailTextBox.Text
            mycommand.Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneTextBox.Text
            mycommand.Parameters.Add("@Address", SqlDbType.NVarChar).Value = AddressTextBox.Text
            mycommand.Parameters.Add("@City", SqlDbType.NVarChar).Value = CityTextBox.Text
            mycommand.ExecuteNonQuery()
            MsgBox("Success")
        Catch ex As System.Data.SqlClient.SqlException
            MsgBox(ex.Message)
        End Try
        myconnect.Close()

输入数据时的问题,我收到了 Success 消息,但是当我检查数据库时,我找不到数据!

我检查了 mdf 文件,发现它是正确的(与我使用的相同)

请提供任何帮助。

4

3 回答 3

2

我知道了

问题出在这一行:

myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB\InvDB.mdf;Integrated Security=True;User Instance=True"

|DataDirectory|用路径替换InvDB.mdf它并且它有效

于 2013-06-17T08:14:47.320 回答
1
Dim query as String = String.Empty
query = "INSERT INTOSupplier (SupplierID, Name, Email,Phone,Address,City) VALUES (@SID, @Name, @Email, @Phone, @Address, @City) "   
Using conn as New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DB\InvDB.mdf;Integrated Security=True;User Instance=True")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            mycommand.Parameters.Add("@SID", SqlDbType.Int).Value = SIDTextBox.Text
        .Parameters.Add("@Name", SqlDbType.NVarChar).Value = NameTextBox.Text
        .Parameters.Add("@Email", SqlDbType.VarChar).Value = EmailTextBox.Text
        .Parameters.Add("@Phone", SqlDbType.VarChar).Value = PhoneTextBox.Text
        .Parameters.Add("@Address", SqlDbType.NVarChar).Value = AddressTextBox.Text
        .Parameters.Add("@City", SqlDbType.NVarChar).Value = CityTextBox.Text            
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

试试这个。

于 2013-06-17T08:17:49.750 回答
-2

我遇到了类似的问题,在我的情况下,应用程序没有对数据库文件所在文件夹的写访问权限。

于 2013-10-13T17:39:28.260 回答