1.需求使用c#访问mysql数据库,实现curd 2.安装和类库引用http://www.tuicool.com/articles/rAbuee 包的下载地址在百度云盘上,也可以通过官方下载 3.数据库操作using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient;using System.Collections;using System.Collections.Generic;using MySql.Data.MySqlClient;using System.Data;namespace ConsoleApplication8{ class Program { static void Main(string[] args) { const string connStr = "server=localhost;database =storecode;user id=root; password=root;";//连接字符串 MySqlConnection mySqlConn = new MySqlConnection(connStr); string sqlStr = "select * from ssc_common_block";//SQL语句 try { mySqlConn.Open(); ;//打开连接 MySqlDataAdapter msda = new MySqlDataAdapter(sqlStr, mySqlConn);//新建MySqlDataAdapter对象 DataSet ds = new DataSet();//新建Dataset对象 msda.Fill(ds);//填充DataSet对象 Console.WriteLine("id\t\tname"); int cnt = ds.Tables[0].Rows.Count;//读取行数 for (int ix = 0; ix != cnt; ++ix) { Console.WriteLine("{0}\t\t{1}", turnString(ds.Tables[0].Rows[ix].ItemArray[0].ToString()), turnString(ds.Tables[0].Rows[ix].ItemArray[3].ToString()));//循环读取数据 注意索引范围 } Console.ReadKey(); } catch (MySqlException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { mySqlConn.Close();//关闭连接 } } //乱码解决 转换函数 public static string turnString(string source) { var en = System.Text.Encoding.GetEncoding("UTF-8"); var bs = en.GetBytes(source); var a = System.Text.Encoding.UTF8.GetString(bs); return a; } }} c#访问mysql数据库 |