应用程序页面在Visual Studio中将数据插入本地SQL Server数据库

时间:2016-10-16 23:32:28

标签: sql-server vb.net

我一直在努力在Visual Studio中创建一个注册页面,我似乎无法让它工作。

  • 数据库名称=用户
  • 要插入数据的列=用户名&密码

当我执行代码时,它会返回消息“Data Saved”,这会让我相信它已经有效,但是当我查看表数据时,没有任何改变。

Public Class SignUp
Dim mysqlConn As Data.SqlClient.SqlConnection
Dim command As Data.SqlClient.SqlCommand

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    mysqlConn = New Data.SqlClient.SqlConnection
    mysqlConn.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
    Dim RowsAffected As Integer
    Try
        mysqlConn.Open()
        Dim query As String = "INSERT INTO [User] (username, password) VALUES (@Username, @Password)"
        command = New SqlClient.SqlCommand(query, mysqlConn)
        Dim paramUsername As New SqlClient.SqlParameter() With {.ParameterName = "@Username", .Value = TextBox1.Text, .Size = 50, .SqlDbType = SqlDbType.VarChar}
        Dim paramPassword As New SqlClient.SqlParameter() With {.ParameterName = "@Password", .Value = TextBox2.Text, .Size = 50, .SqlDbType = SqlDbType.VarChar}

        command.Parameters.Add(paramUsername)
        command.Parameters.Add(paramPassword)

        RowsAffected = command.ExecuteNonQuery

        mysqlConn.Close()

        If 0 < RowsAffected 
           Then MessageBox.Show("Data Saved")
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        mysqlConn.Dispose() 'closes connection  
    End Try 

1 个答案:

答案 0 :(得分:0)

整个用户实例和AttachDbFileName = 方法存在缺陷 - 充其量!在Visual Studio中运行应用程序时,它将复制.mdf文件(从App_Data目录到输出目录 - 通常是.\bin\debug - 应用程序运行的地方)和最有可能,您的INSERT工作正常 - 但您最后只是查看错误的.mdf文件

如果你想坚持这种方法,那么尝试在mySqlConn.Close()调用上设置一个断点 - 然后用SQL Server Mgmt Studio Express检查.mdf文件 - 我几乎可以肯定你的数据在那里。