分享

C# 连接MySQL数据库并进行相关操作

 小小243 2013-12-13

C# 连接MySQL数据库并进行相关操作

 

       之前在C#使用OleDb读取Excel,生成SQL语句 中只是生成SQL语句,没有连接数据库执行。后面举得这样不方便,让改成直接插入数据库,还将了生成对应的实体类的功能。

       C#连接数据库方法有很多,在①中说道了三种连接数据方法和示例,我采用的是MySQL自己的组件mysql.data.dll来连接数据库的,并封装了一些函数,虽然只用到了GetSchema(取出数据的表)和ExecuteSQLFile(执行sql文件)两个功能,其他具体的功能可以参考官方的Document。

 

 

       当然一般都不会一次搞定了,在生成实体类的要获取表的字段信息,就出现获取的字段为null,后面自己琢磨和测试,发现是GetSchema中的字符串数组参数和文档中规定的顺序不一致,所以无法匹配,就返回null。下面是代码:

C#代码  收藏代码
  1. DataTable dt = dbhelper.GetSchema("Databases"),dt1;  
  2.             TreeNode tn,tn1;  
  3.             string temp;  
  4.             foreach(DataRow dr in dt.Rows)  
  5.             {  
  6.                 temp = dr[1].ToString();  
  7.                 tn = new MyNode(dbhelper, temp);  
  8.                 //tn.Text = temp;  
  9.                 dt1 = dbhelper.GetSchema("Tables",new string[4]{null,temp,null,null});  
  10.                 foreach (DataRow dr1 in dt1.Rows)  
  11.                 {  
  12.                     tn1 = new MyNode(dbhelper,dr1[2].ToString());  
  13.                     tn.Nodes.Add(tn1);  
  14.                 }  
  15.                 tv.Nodes.Add(tn);  
  16.             }  

       另外一个功能,其实是Excel文件导出SQL语句,然后执行,代码很简单,在下面的ExecuteSQLFile函数可以看到,但是也碰到了一个问题:

在 MySql.Data.MySqlClient.MySqlStream.ReadPacket()

   在 MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)

   在 MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)

   在 MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)

   在 MySql.Data.MySqlClient.MySqlDataReader.NextResult()

   在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)

   在 MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()

   在 MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()

   在 ReadXlsxData.DBConnect.ExecuteSQLFile(String fileName) 

 

       对我这个完全没有数据库经验的来说,根本看不到问题所在,只有google,虽然在stackoverflow上有这个问题但是没有解决,无奈之下,只有自己琢磨,在google到②文章,看了下,好像看到有说版本的问题,然后我就索性下载最新的mysql.data.dll,竟然出现是数据库未连接成功,原因是在我XML解析的时候错误。然后修改这部分竟然就执行成功了。

 

       惊喜之余,附上网上找(支持Insert,Update,Backup,Restore,Delete,Select等操作,完全可以自己加工写一个图形界面数据库管理工具了哈)加我写ExecuteSQLFile的代码:

C#代码  收藏代码
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows.Forms;  
  6. using System.Diagnostics;  
  7. using System.IO;  
  8. //Add MySql Library  
  9. using MySql.Data.MySqlClient;  
  10. using System.Data;  
  11.   
  12. namespace ReadXlsxData  
  13. {  
  14.     class DBConnect  
  15.     {  
  16.         private MySqlConnection connection;  
  17.         private string server;  
  18.         private string database;  
  19.         private string uid;  
  20.         private string password;  
  21.         private string port;  
  22.         //private string database;  
  23.   
  24.   
  25.   
  26.         //Initialize values  
  27.         public void Initialize(string server, string database,string uid, string password, string port)  
  28.         {  
  29.             //server = "localhost";  
  30.             //database = "connectcsharptomysql";  
  31.             //uid = "username";  
  32.             //password = "password";  
  33.             this.server = server;  
  34.             this.uid = uid;  
  35.             this.password = password;  
  36.             this.port = port;  
  37.             this.database = database;  
  38.             string connectionString = "Data Source=" + server + ";" + "port=" + port + ";" + "Database=" + database + ";" + "User Id=" + uid + ";" + "Password=" + password + ";" + "CharSet = utf8"; ;  
  39.             connection = new MySqlConnection(connectionString);  
  40.         }  
  41.   
  42.   
  43.         //open connection to database  
  44.         public bool OpenConnection()  
  45.         {  
  46.             try  
  47.             {  
  48.                 connection.Open();  
  49.                 return true;  
  50.             }  
  51.             catch (MySqlException ex)  
  52.             {  
  53.                 //When handling errors, you can your application's response based on the error number.  
  54.                 //The two most common error numbers when connecting are as follows:  
  55.                 //0: Cannot connect to server.  
  56.                 //1045: Invalid user name and/or password.  
  57.                 switch (ex.Number)  
  58.                 {  
  59.                     case 0:  
  60.                         MessageBox.Show("Cannot connect to server.  Contact administrator");  
  61.                         break;  
  62.   
  63.                     case 1045:  
  64.                         MessageBox.Show("Invalid username/password, please try again");  
  65.                         break;  
  66.                 }  
  67.                 return false;  
  68.             }  
  69.         }  
  70.   
  71.         //Close connection  
  72.         public bool CloseConnection()  
  73.         {  
  74.             try  
  75.             {  
  76.                 connection.Close();  
  77.                 return true;  
  78.             }  
  79.             catch (MySqlException ex)  
  80.             {  
  81.                 MessageBox.Show(ex.Message);  
  82.                 return false;  
  83.             }  
  84.         }  
  85.   
  86.         public DataTable GetSchema(string str, string[] restri)  
  87.         {  
  88.             return connection.GetSchema(str, restri);  
  89.         }  
  90.         public DataTable GetSchema(string str)  
  91.         {  
  92.             return connection.GetSchema(str);  
  93.         }  
  94.         // Get Database List  
  95.   
  96.         //Insert statement  
  97.         public void Insert()  
  98.         {  
  99.             string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";  
  100.   
  101.             //open connection  
  102.             if (this.OpenConnection() == true)  
  103.             {  
  104.                 //create command and assign the query and connection from the constructor  
  105.                 MySqlCommand cmd = new MySqlCommand(query, connection);  
  106.                 //Execute command  
  107.                 cmd.ExecuteNonQuery();  
  108.                 //close connection  
  109.                 this.CloseConnection();  
  110.             }  
  111.         }  
  112.   
  113.         //Update statement  
  114.         public void Update()  
  115.         {  
  116.             string query = "UPDATE tableinfo SET name='Joe', age='22' WHERE name='John Smith'";  
  117.   
  118.             //Open connection  
  119.             if (this.OpenConnection() == true)  
  120.             {  
  121.                 //create mysql command  
  122.                 MySqlCommand cmd = new MySqlCommand();  
  123.                 //Assign the query using CommandText  
  124.                 cmd.CommandText = query;  
  125.                 //Assign the connection using Connection  
  126.                 cmd.Connection = connection;  
  127.   
  128.                 //Execute query  
  129.                 cmd.ExecuteNonQuery();  
  130.   
  131.                 //close connection  
  132.                 this.CloseConnection();  
  133.             }  
  134.         }  
  135.   
  136.         //Delete statement  
  137.         public void Delete()  
  138.         {  
  139.             string query = "DELETE FROM tableinfo WHERE name='John Smith'";  
  140.   
  141.             if (this.OpenConnection() == true)  
  142.             {  
  143.                 MySqlCommand cmd = new MySqlCommand(query, connection);  
  144.                 cmd.ExecuteNonQuery();  
  145.                 this.CloseConnection();  
  146.             }  
  147.         }  
  148.   
  149.         //Select statement  
  150.         public List<string>[] Select()  
  151.         {  
  152.             string query = "SELECT * FROM tableinfo";  
  153.   
  154.             //Create a list to store the result  
  155.             List<string>[] list = new List<string>[3];  
  156.             list[0] = new List<string>();  
  157.             list[1] = new List<string>();  
  158.             list[2] = new List<string>();  
  159.   
  160.             //Open connection  
  161.             if (this.OpenConnection() == true)  
  162.             {  
  163.                 //Create Command  
  164.                 MySqlCommand cmd = new MySqlCommand(query, connection);  
  165.                 //Create a data reader and Execute the command  
  166.                 MySqlDataReader dataReader = cmd.ExecuteReader();  
  167.   
  168.                 //Read the data and store them in the list  
  169.                 while (dataReader.Read())  
  170.                 {  
  171.                     list[0].Add(dataReader["id"] + "");  
  172.                     list[1].Add(dataReader["name"] + "");  
  173.                     list[2].Add(dataReader["age"] + "");  
  174.                 }  
  175.                 //close Data Reader  
  176.                 dataReader.Close();  
  177.                 //close Connection  
  178.                 this.CloseConnection();  
  179.                 //return list to be displayed  
  180.                 return list;  
  181.             }  
  182.             else  
  183.             {  
  184.                 return list;  
  185.             }  
  186.         }  
  187.   
  188.         //Count statement  
  189.         public int Count()  
  190.         {  
  191.             string query = "SELECT Count(*) FROM tableinfo";  
  192.             int Count = -1;  
  193.             //Open Connection  
  194.             if (this.OpenConnection() == true)  
  195.             {  
  196.                 //Create Mysql Command  
  197.                 MySqlCommand cmd = new MySqlCommand(query, connection);  
  198.   
  199.                 //ExecuteScalar will return one value  
  200.                 Count = int.Parse(cmd.ExecuteScalar() + "");  
  201.                 //close Connection  
  202.                 this.CloseConnection();  
  203.                 return Count;  
  204.             }  
  205.             else  
  206.             {  
  207.                 return Count;  
  208.             }  
  209.         }  
  210.   
  211.         //Backup  
  212.         public void Backup()  
  213.         {  
  214.             try  
  215.             {  
  216.                 DateTime Time = DateTime.Now;  
  217.                 int year = Time.Year;  
  218.                 int month = Time.Month;  
  219.                 int day = Time.Day;  
  220.                 int hour = Time.Hour;  
  221.                 int minute = Time.Minute;  
  222.                 int second = Time.Second;  
  223.                 int millisecond = Time.Millisecond;  
  224.   
  225.                 //Save file to C:\ with the current date as a filename  
  226.                 string path;  
  227.                 path = "C:\\" + year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";  
  228.                 StreamWriter file = new StreamWriter(path);  
  229.   
  230.   
  231.                 ProcessStartInfo psi = new ProcessStartInfo();  
  232.                 psi.FileName = "mysqldump";  
  233.                 psi.RedirectStandardInput = false;  
  234.                 psi.RedirectStandardOutput = true;  
  235.                 psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", uid, password, server, database);  
  236.                 psi.UseShellExecute = false;  
  237.   
  238.                 Process process = Process.Start(psi);  
  239.   
  240.                 string output;  
  241.                 output = process.StandardOutput.ReadToEnd();  
  242.                 file.WriteLine(output);  
  243.                 process.WaitForExit();  
  244.                 file.Close();  
  245.                 process.Close();  
  246.             }  
  247.             catch (IOException ex)  
  248.             {  
  249.                 MessageBox.Show("Error , unable to backup!");  
  250.             }  
  251.         }  
  252.   
  253.         //Restore  
  254.         public void Restore()  
  255.         {  
  256.             try  
  257.             {  
  258.                 //Read file from C:\  
  259.                 string path;  
  260.                 path = "C:\\MySqlBackup.sql";  
  261.                 StreamReader file = new StreamReader(path);  
  262.                 string input = file.ReadToEnd();  
  263.                 file.Close();  
  264.   
  265.   
  266.                 ProcessStartInfo psi = new ProcessStartInfo();  
  267.                 psi.FileName = "mysql";  
  268.                 psi.RedirectStandardInput = true;  
  269.                 psi.RedirectStandardOutput = false;  
  270.                 psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}", uid, password, server, database);  
  271.                 psi.UseShellExecute = false;  
  272.   
  273.                 Process process = Process.Start(psi);  
  274.                 process.StandardInput.WriteLine(input);  
  275.                 process.StandardInput.Close();  
  276.                 process.WaitForExit();  
  277.                 process.Close();  
  278.             }  
  279.             catch (IOException ex)  
  280.             {  
  281.                 MessageBox.Show("Error , unable to Restore!");  
  282.             }  
  283.         }  
  284.         //Execute Sql File  
  285.         public void ExecuteSQLFile(string fileName)  
  286.         {  
  287.             string sql = File.ReadAllText(fileName, Encoding.UTF8);  
  288.             MySqlCommand myCommand = new MySqlCommand(sql);  
  289.             myCommand.Connection = connection;  
  290.             if (this.OpenConnection() == true)  
  291.             {  
  292.                 myCommand.ExecuteNonQuery();  
  293.                 //MessageBox.Show("..........");  
  294.                 this.CloseConnection();  
  295.             }  
  296.               
  297.   
  298.         }  
  299.   
  300.     }  
  301. }  

       

       连接数据库,生成数据库表树(界面图),是参照网上一个软件做的,因为没有给代码,就自己参照着来山寨了一把:

   

小结:

       其实我到现在对数据库和SQL语句都不了解,因为之前大学没有学过,虽然工作中在服务器业务中也有用到SQL语句,但还是不熟。所以在上面初始化数据库连接语句时:

C#代码  收藏代码
  1. string connectionString = "Data Source=" + server + ";" + "port=" + port + ";" + "Database=" + database + ";" + "User Id=" + uid + ";" + "Password=" + password + ";" + "CharSet = utf8";   

 这个,我之前的一个版本不是这么写的, Data Source 原来是 Server 而 User Id 原来是uid ,因为不懂,只能是哪个行就到哪,想着等着有时间好好琢磨下。

       数据库操作或SQL语句其实不难,实际工作也很少会说考虑性能这方面的东西,对数据库的内部工作原理没有个谱,用起来只能依葫芦画瓢,跟写上面数据库连接语句,我只有去google,找下人家怎么写,或者是去找官方的Example。所以希望以后能对数据库知根知底,如果您有这方面的什么推荐,希望能收到您的留言,谢谢!

 

        转载在文首注明出处:http://dsqiu./blog/1964567

更多精彩请关注D.S.Qiu的博客和微博(ID:静水逐风)

 

参考:

 ①C#+Mysql+Mono:http://blog.donews.com/monoer/archive/2006/06/06/904285.aspx

easy5: http://www.cnblogs.com/easy5weikai/archive/2012/12/06/2805558.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多