如何将数据输入保存到MySQL数据库

时间:2012-04-01 13:40:00

标签: mysql vb.net vb.net-2010

我有一项任务,我必须使用Visual Basic .NET开发Windows应用程序。从我设计的表单中,它应该将所有记录保存在MySQL数据库的表中。我该怎么做?这是我到目前为止所得到的:

Imports System.Data
Imports System.Data.SqlClient

Public Class AddMember
    Dim con As New SqlConnection
    Dim cmd As New SqlCommand

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        con.ConnectionString = "Data Source=|DataDirectory|\127.0.0.1"

        con.Open()

        cmd.Connection = con
        cmd.CommandText = "INSERT INTO memberdetails (ID, Name, Surname, Age, Gender, Contact, Address) VALUES (@ID, @Name, @Surname, @Age, @Gender, @Contact, @Address)"

        cmd.Parameters.AddWithValue("@ID", TextBox1.Text)
        cmd.Parameters.AddWithValue("@Name", TextBox2.Text)
        cmd.Parameters.AddWithValue("@Surname", TextBox3.Text)
        cmd.Parameters.AddWithValue("@Age", TextBox4.Text)
        cmd.Parameters.AddWithValue("@Gender", ComboBox1.Text)
        cmd.Parameters.AddWithValue("@Contact", TextBox6.Text)
        cmd.Parameters.AddWithValue("@Address", TextBox7.Text)
        cmd.ExecuteNonQuery()

        con.Close()

        MsgBox("Added Successfully")
    End Sub
End Class

con.Open() - 错误26

1 个答案:

答案 0 :(得分:0)

我认为这与您的连接字符串有关。尝试这种连接字符串格式:

con.ConnectionString = "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;" 

由于您的数据库服务器是MySQL,因此不应使用System.Data.SqlClient命名空间,而应使用MySql.Data.MySqlClient命名空间。