C#連接MySql數據庫代碼


之前學JAVA的時候,老師講數據庫的時候,講到可以用一個類來連接數據庫,叫做Dao層,今天要用C#做上位機,也有一些數據要寫到數據庫中去,我就想,能不能也給C#寫一個這樣的Dao層來連接數據庫,我就去百度,結果看到有一個帖子寫了這樣的,我就把代碼復制下來看,但是他直接在這個類里面處理數據了,於是我綜合了Java的代碼,和這份代碼,改出來了現在連接數據庫的類DButil

 1  public class DButil
 2     {
 3         MySqlConnection mycon = null;//連接
 4         MySqlCommand mycmd = null;//Sql命令
 5         string constr = "server=localhost;User Id=root;password=zp730238;Database=smarthome";
 6         MySqlDataReader rs = null;
 7         public DButil()
 8         {
 9             
10             // TODO: 在此處添加構造函數邏輯
11             
12         }
13         public MySqlConnection getMySqlCon()
14         {
15             if(mycon == null)
16             {
17                 mycon = new MySqlConnection(constr);
18                 mycon.Open();
19             }
20             return mycon;
21         }
22         public void closeConnection()
23         {
24             if (mycon != null)
25             {
26                 mycon.Close();
27             }
28             
29         }
30         public MySqlCommand getMySqlCommand(String sql, MySqlConnection con)
31         {
32             if(mycmd == null)
33             {
34                 mycmd = new MySqlCommand(sql, con);
35             }
36             else
37             {
38                 mycmd.CommandText = sql;
39                 mycmd.Connection = con;
40             }
41             
42             return mycmd;
43         }
44         public MySqlDataReader getResultset(String sql)
45         {
46 
47             try
48             {
49                 mycon = getMySqlCon();
50                 mycmd = getMySqlCommand(sql, mycon);
51                 rs = mycmd.ExecuteReader();
52                 return rs;
53             }
54             catch (Exception)
55             {
56                 mycon.Close();
57                 return null;
58             }
59 
60         }
61          //<summary>
62          //添加數據
63          //</summary>
64          //<param name="mySqlCommand"></param>
65         public  int  getUpdata(String sql)
66         {
67             int num = 0; 
68             try
69             {
70                 mycon = getMySqlCon();
71                 mycmd = getMySqlCommand(sql,mycon);
72                 num  = mycmd.ExecuteNonQuery();
73                 
74             }
75             catch (Exception ex)
76             {
77                //Todo:
78           //      Console.WriteLine("error");
79             }
80             return num;
81         }
82     }
View Code

這個類主要包括四個屬性,五個方法,

MySqlConnection mycon = null;//連接
MySqlCommand mycmd = null;//Sql命令
string constr = "server=localhost;User Id="";password="";Database=""";//Sql連接配置
MySqlDataReader rs = null;//返回的結果集

五個方法分別是,獲取連接,關閉連接,獲取執行命令,查詢數據庫,懶得寫了,看不懂直接聯系我吧。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM