c#连接Mysql数据库 Connect to mySQL in C#
作者:admin 日期:2009-01-05
Instructions:
1) Download and install the connector: url=http://dev.mysql.com/downloads/connector/net/1.0.html
2) Create a test project
3)Next add reference to: MySql.Data
4) Next add "using MySql.Data.MySqlClient;"
/// <summary>
/// Method for connection to a mySQL database. You
/// need to download the mySQL Connector located at
/// http://dev.mysql.com/downloads/connector/net/1.0.html]
///
/// NOTE: I am a big supporter of having the connection
/// stored in the web.config, not inline like this
/// </summary>
/// <param name="server"></param>
private void connectoToMySql(string server)
{
//set your connection string.
//NOTE: I am a big supporter of having the connection
//stored in the web.config, not inline like this
string connString = "SERVER=" + server + ";" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
//create your mySQL connection
MySqlConnection cnMySQL = new MySqlConnection(connString);
//create your mySql command object
MySqlCommand cmdMySQL = cnMySQL.CreateCommand();
//create your mySQL reeader object
MySqlDataReader reader;
//set the command text (query) of the
//mySQL command object
cmdMySQL.CommandText = "select * from mycustomers";
//open the mySQL connection
cnMySQL.Open();
//execute the reader, thus retrieving the data
reader = cmdMySQL.ExecuteReader();
//while theres data keep reading
while (reader.Read())
{
string thisrow = "";
for (int i = 0; i < reader.FieldCount; i++)
thisrow += reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
cnMySQL.Close();
}
广告位