使用c#连接到mysql

时间:2012-10-11 10:12:25

标签: c# mysql

请原谅我提出一个主要问题。我需要使用c#连接到此链接http://sunspares.millenniumit.com/phpmyadmin/。它是MySQL的,我需要在'库存'数据库中访问一个名为'spares'的表。任何人都可以帮我用C#初始化这个连接。我找到了下面的编码,但我很困惑如何提供我需要连接的确切服务器以及表格

con = mysql_connect("localhost","username","password");

2 个答案:

答案 0 :(得分:4)

  1. 安装mysql connector/net

  2. 创建一个新项目。

  3. 添加对MySql.Data的引用。

  4. 添加using MySql.Data.MySqlClient;

  5. 将以下代码添加到您的应用程序中:

    private void button1_Click(object sender, System.EventArgs e)
    {
            string MyConString = @"SERVER=localhost;
                DATABASE=mydatabase;
                UID=testuser;
                PASSWORD=testpassword;";
            MySqlConnection connection = new MySqlConnection(MyConString);
            MySqlCommand command = connection.CreateCommand();
            MySqlDataReader Reader;
            command.CommandText = "select * from mycustomers";
            connection.Open();
            Reader = command.ExecuteReader();
            while (Reader.Read())
            {
                string thisrow = "";
                for (int i= 0;i<Reader.FieldCount;i++)
                        thisrow+=Reader.GetValue(i).ToString() + ",";
                listBox1.Items.Add(thisrow);
            }
            connection.Close();
    }
    

答案 1 :(得分:0)

 <connectionStrings>
    <add name="MySQLConnectionString" connectionString="server=localhost;User      Id=root;pwd=;database=data1;" providerName="MySql.Data.MySqlClient"/>
  </connectionStrings>

-----------------------
using MySql.Data.MySqlClient;
...
MySqlConnection Conn = new MySqlConnection();
Conn = new MySqlConnection(ConnStr);