1.安装下载mysql
2.安装mysqlworkbench
3.安装mysql for .net
4.在C#项目中引用mysql for .net动态链接库
5.自己写了一个简单数据库连接操作类
usingSystem;
usingSystem.Data;
usingMySql.Data.MySqlClient;
namespacemysqltest
{
class sqlclass
{
public MySqlConnection mysqlcon;
public void getMySqlCon()
{
StringmysqlStr = "Host=127.0.0.1;Database=student;UserId=lls;Password=123456;CharSet=utf8;port=3306";
mysqlcon = newMySqlConnection(mysqlStr);
mysqlcon.Open();
}
public DataTable getResultset(stringmysqlquery)
{
MySqlCommandmySqlCommand =new MySqlCommand(mysqlquery,mysqlcon);
MySqlDataReaderreader = mySqlCommand.ExecuteReader();
try
{
if(reader.HasRows)
{
DataTabledt =new DataTable();
//读取SqlDataReader里的内容
dt.Load(reader);
//关闭对象和连接
reader.Close();
mysqlcon.Close();
returndt;
}
returnnull;
}
catch(Exception)
{
reader.Close();
mysqlcon.Close();
Console.WriteLine("查询失败了!");
returnnull;
}
finally
{
reader.Close();
mysqlcon.Close();
}
}
}
}
读取datatable的内容:
DataTablerestable = sqlcontest.getResultset(query);
stringtest = restable.Columns[0].ColumnName;//获取第0列的列名
intnumber = restable.Columns.Count; //获取列的个数
Console.WriteLine(test);
Console.WriteLine(number);
DataRow[]drs = restable.Select();
foreach(DataRow drindrs)
{
Console.WriteLine("{0},{1},{2}", dr[0].ToString(),dr[1].ToString(), dr[2].ToString());
}