[C#]获取连接MySql数据库及常用的CRUD操作
测试如下:
首先添加引用:MySql.Data.dll
链接:http://pan.baidu.com/s/1dEQgLpf 密码:bnyu
*将链接数据库的信息放入配置文件中(app.config)
1 <appSettings> 2 <add key="mysql" value="server=127.0.0.1;User Id=******;password=******;Database="******"/> 3 </appSettings>
*在程序启动时进行启动
1 private string mysqlString = ConfigurationManager.AppSettings["mysql"].ToString();
①建立mysql数据库链接
1 //建立mysql数据库链接 2 public MySqlConnection getMySqlConn() 3 { 4 //string constr = "server=localhost;User Id=root;password=123456;Database=qqmusicdistinct";
5 string constr = mysqlString; 6 MySqlConnection mycon = new MySqlConnection(constr); 7 return mycon; 8 }
②建立执行命令语句对象
1 //建立执行命令语句对象 2 public MySqlCommand getSqlCommand(String sql, MySqlConnection mysql) 3 { 4 MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql); 5 return mySqlCommand; 6 }
③编写sql语句,对数据做相应处理
1 //编写sql语句,对数据做相应处理 2 public void setData() 3 { 4 MySqlConnection mysql = getMySqlConn(); 5 //查询sql 6 String sqlSearch = "select * from student"; 7 //插入sql 8 //String sqlInsert = "insert into student values (12,'张三',25,'大专')"; 9 //修改sql 10 //String sqlUpdate = "update student set name='李四' where id= 3"; 11 //删除sql 12 //String sqlDel = "delete from student where id = 12"; 13 14 //四种语句对象 15 MySqlCommand mySqlCommand = getSqlCommand(sqlSearch, mysql); 16 //MySqlCommand mySqlCommand = getSqlCommand(sqlInsert, mysql); 17 //MySqlCommand mySqlCommand = getSqlCommand(sqlUpdate, mysql); 18 //MySqlCommand mySqlCommand = getSqlCommand(sqlDel, mysql); 19 20 mysql.Open(); 21 22 getResultset(mySqlCommand); 23 //getInsert(mySqlCommand); 24 //getUpdate(mySqlCommand); 25 //getDel(mySqlCommand); 26 //记得关闭 27 mysql.Close(); 28 }
④Ⅰ.查询并获得结果集并遍历
1 //查询并获得结果集并遍历 2 public void getResultset(MySqlCommand mySqlCommand) 3 { 4 MySqlDataReader reader = mySqlCommand.ExecuteReader(); 5 try 6 { 7 while (reader.Read()) 8 { 9 if (reader.HasRows) 10 { 11 //MessageBox.Show("歌曲名:" + reader.GetString(1) + "|歌手:" + reader.GetString(2)); 12 } 13 } 14 } 15 catch (Exception) 16 { 17 MessageBox.Show("查询失败了!"); 18 } 19 finally 20 { 21 reader.Close(); 22 } 23 }
④Ⅱ.添加数据
1 //添加数据 2 public static void getInsert(MySqlCommand mySqlCommand) 3 { 4 try 5 { 6 mySqlCommand.ExecuteNonQuery(); 7 } 8 catch (Exception ex) 9 { 10 String message = ex.Message; 11 Console.WriteLine("插入数据失败了!" + message); 12 } 13 14 }
④Ⅲ.修改数据
1 //修改数据 2 public static void getUpdate(MySqlCommand mySqlCommand) 3 { 4 try 5 { 6 mySqlCommand.ExecuteNonQuery(); 7 } 8 catch (Exception ex) 9 { 10 String message = ex.Message; 11 Console.WriteLine("修改数据失败了!" + message); 12 } 13 }
④Ⅳ.删除数据
1 //删除数据 2 public static void getDel(MySqlCommand mySqlCommand) 3 { 4 try 5 { 6 mySqlCommand.ExecuteNonQuery(); 7 } 8 catch (Exception ex) 9 { 10 String message = ex.Message; 11 Console.WriteLine("删除数据失败了!" + message); 12 } 13 }