连接数据库、执行sql语句需要的API,数据库都有提供相关动态链接库。
帮助文档在C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation下的ConnectorNET.chm
1.添加动态链接库文件:
安装数据库MySQL时要选中Connector.NET 6.9的安装,将C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies里v4.0或v4.5中的MySql.Data.dll导入项目。v4.0和v4.5,对应Visual Studio具体项目 属性-应用程序-目标框架 里的.NET Framework的版本号
2.建立连接(MySqlConnection)
using MySql.Data.MySqlClient; String connetStr = "server=127.0.0.1;port=3306;user=root;password=root; database=minecraftdb;"; // server=127.0.0.1/localhost 代表本机,端口号port默认是3306可以不写 MySqlConnection conn = new MySqlConnection(connetStr); try { conn.Open();//打开通道,建立连接,可能出现异常 Console.WriteLine("已经建立连接"); //在这里使用代码对数据库进行增删查改 } catch (MySqlException ex) { Console.WriteLine(ex.Message); } finally { conn.Close(); }
3.捕捉异常(MySqlException)
连接错误时MySqlConnection会返回一个MySqlException,其中包括2个变量:
Message: A message that describes the current exception.
Number: The MySQL error number. (0: Cannot connect to server. 1045: Invalid user name and/or password.)
catch (MySqlException ex) { switch (ex.Number) { case 0: Console.WriteLine("Cannot connect to server. Contact administrator"); break; case 1045: Console.WriteLine("Invalid username/password, please try again"); break; } }
4.增删查改的代码(MySqlCommand、MySqlDataReader)
(1) 查询
查询条件固定
string sql= "select * from user"; MySqlCommand cmd = new MySqlCommand(sql,conn); MySqlDataReader reader =cmd.ExecuteReader();//ExecuteReader()用于生成一个MySqlDataReader对象 while (reader.Read())//读取下一页数据,返回值是bool { //Console.WriteLine(reader[0].ToString() + reader[1].ToString() + reader[2].ToString()); //Console.WriteLine(reader.GetInt32(0)+reader.GetString(1)+reader.GetString(2)); Console.WriteLine(reader.GetInt32("userid") + reader.GetString("username") + reader.GetString("password"));//推荐这种方式 }
需要查询返回一个值
string sql = "select count(*) from user"; MySqlCommand cmd = new MySqlCommand(sql, conn); Object result=cmd.ExecuteScalar();//执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。select语句无记录返回时,ExecuteScalar()返回NULL值 if (result != null) { int count = int.Parse(result.ToString()); }
查询条件不固定
//string sql = "select * from user where username=‘"+username+"‘ and password=‘"+password+"‘"; //我们自己按照查询条件去组拼 string sql = "select * from user where username=@para1 and password=@para2";//在sql语句中定义parameter,然后再给parameter赋值 MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("para1", username); cmd.Parameters.AddWithValue("para2", password); MySqlDataReader reader = cmd.ExecuteReader(); if (reader.Read())//如果用户名和密码正确则能查询到一条语句,即读取下一行返回true { return true; }
(2) 插入、删除、更改
string sql = "insert into user(username,password,registerdate) values(‘啊宽‘,‘123‘,‘"+DateTime.Now+"‘)"; //string sql = "delete from user where userid=‘9‘"; //string sql = "update user set username=‘啊哈‘,password=‘123‘ where userid=‘8‘"; MySqlCommand cmd = new MySqlCommand(sql,conn); int result =cmd.ExecuteNonQuery();//3.执行插入、删除、更改语句。执行成功返回受影响的数据的行数,返回1可做true判断。执行失败不返回任何数据,报错,下面代码都不执行
5.事务(MySqlTransaction)
String connetStr = "server=127.0.0.1;user=root;password=root;database=minecraftdb;"; MySqlConnection conn = new MySqlConnection(connetStr); conn.Open();//必须打开通道之后才能开始事务 MySqlTransaction transaction = conn.BeginTransaction();//事务必须在try外面赋值不然catch里的transaction会报错:未赋值 Console.WriteLine("已经建立连接"); try { string date = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day; string sql1= "insert into user(username,password,registerdate) values(‘啊宽‘,‘123‘,‘" + date + "‘)"; MySqlCommand cmd1 = new MySqlCommand(sql1,conn); cmd1.ExecuteNonQuery(); string sql2 = "insert into user(username,password,registerdate) values(‘啊宽‘,‘123‘,‘" + date + "‘)"; MySqlCommand cmd2 = new MySqlCommand(sql2, conn); cmd2.ExecuteNonQuery(); } catch (MySqlException ex) { Console.WriteLine(ex.Message); transaction.Rollback();//事务ExecuteNonQuery()执行失败报错,username被设置unique conn.Close(); } finally { if (conn.State != ConnectionState.Closed) { transaction.Commit();//事务要么回滚要么提交,即Rollback()与Commit()只能执行一个 conn.Close(); } }
总结:
MySQL动态链接库提供了8个类,而上面常用操作只用到了这4个类
(1)MySqlConnection: 连接MySQL服务器数据库。
(2)MySqlCommand:执行一条sql语句
a.ExecuteReader——用于查询数据库。结果通常是MySqlDataReader对象中返回。
b.ExecuteNonQuery——用于插入和删除数据。
c.ExecuteScalar——用于返回一个值。
(3)MySqlDataReader: 包含sql语句执行的结果,并提供一个方法从结果中阅读一行
(4)MySqlTransaction: 代表一个SQL事务在一个MySQL数据库。
(5)MySqlException: MySQL报错时返回的Exception
还有这3个类 的相关操作未涉及, 大家可以去看帮助文档ConnectorNET.chm在C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation里面
MySqlCommandBuilder: Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database.
MySqlDataAdapter: Represents a set of data commands and a database connection that are used to fill a data set and update a MySQL database.
MySqlHelper: Helper class that makes it easier to work with the provider.