在C#中使用MySQL进行数据库操作,可以通过以下步骤实现:
引用MySQL Connector/.NET库。
使用MySqlConnection对象连接到数据库,可以使用以下语句:
MySqlConnection conn = new MySqlConnection("Server=127.0.0.1;Database=testdb;Uid=root;Pwd=123456;");
其中,Server指定MySQL服务器地址,Database指定数据库名称,Uid指定MySQL用户名,Pwd指定MySQL密码。
- 打开数据库连接:
conn.Open();
- 创建MySqlCommand对象,用于执行SQL语句:
MySqlCommand mySqlCommand = conn.CreateCommand();
- 执行SQL语句,读取数据或将数据写入数据库:
mySqlCommand.CommandText = "SELECT * FROM table1"; MySqlDataReader reader = mySqlCommand.ExecuteReader(); while (reader.Read()) { //读取数据 }
mySqlCommand.CommandText = "INSERT INTO table1 VALUE('test')"; mySqlCommand.ExecuteNonQuery();
完整的示例代码如下:
using System; using MySql.Data.MySqlClient;
namespace MySQL_Test { class Program { static void Main(string[] args) { string connStr = "Server=127.0.0.1;Database=testdb;Uid=root;Pwd=123456;"; MySqlConnection conn = new MySqlConnection(connStr); try { conn.Open(); MySqlCommand mySqlCommand = conn.CreateCommand(); mySqlCommand.CommandText = "SELECT * FROM table1"; MySqlDataReader reader = mySqlCommand.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["col1"] + "\t" + reader["col2"]); }
mySqlCommand.CommandText = "INSERT INTO table1 VALUE('test')";
mySqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();
}
}
}
}