C# 连接MySQL

      用MySQLDriverCS连接MySQL数据库 :

      C#用MySQLDriverCS连接MySql需要两个库文件:libmySQL.dll  MySQLDriverCS.DLL,然后在项目中添加引用  MySQLDriverCS.DLL,再在程序中添加using MySQLDriverCS;然后就进行MySql操作了,如下操作:

 

   MySQLConnection conn = null;

   conn = new MySQLConnection(new MySQLConnectionString("localhost", "Menu","root", "123").AsString);

   conn.Open();


   MySQLCommand comm = new MySQLCommand("set names gb2312", conn);

   comm .ExecuteNonQuery();


   string sql = "select * from table_level ";

   MySQLDataAdapter mda = new MySQLDataAdapter(sql, conn);


   DataSet ds = new DataSet();

   mda.Fill(ds, "table1");


   this.dataGridView1.DataSource = ds.Tables["table1"];

   conn.Close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C连接MySQL需要使用MySQL连接器,并且需要引用System.Data命名空间和MySql.Data.MySqlClient命名空间。下面是一个示例代码,展示了如何使用C#连接MySQL数据库: ```csharp using System; using System.Data; using MySql.Data.MySqlClient; public class MySQLConnector { private MySqlConnection connection; public MySQLConnector(string connectionString) { connection = new MySqlConnection(connectionString); } public void Connect() { try { connection.Open(); Console.WriteLine("数据库连接成功!"); } catch (Exception ex) { Console.WriteLine("数据库连接失败:" + ex.Message); } } public void Disconnect() { connection.Close(); Console.WriteLine("数据库连接已断开!"); } public DataTable SelectData(string tableName, string columns, string condition) { DataTable dataTable = new DataTable(); string sql = ""; if (string.IsNullOrEmpty(condition)) { sql = "SELECT " + columns + " FROM " + tableName; } else { sql = "SELECT " + columns + " FROM " + tableName + " WHERE " + condition; } MySqlCommand command = new MySqlCommand(sql, connection); MySqlDataAdapter adapter = new MySqlDataAdapter(command); adapter.Fill(dataTable); return dataTable; } public int UpdateData(string tableName, string columnsAndValues, string condition) { string sql = "UPDATE " + tableName + " SET " + columnsAndValues + " WHERE " + condition; MySqlCommand command = new MySqlCommand(sql, connection); int rowsAffected = command.ExecuteNonQuery(); return rowsAffected; } } ``` 以上代码展示了一个MySQL连接器的基本操作,包括连接数据库、断开连接、查询数据和修改数据。你可以根据自己的需求进行相应的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值