C# MariaDB 連接,關閉,創建、增、刪、查、改


最近項目用到C# 以及MariaDB相關知識,在此小計一下。

關於MariaDB的安裝使用參照以下連接文檔:

MariaDB安裝與使用_HeidiSQL工具_IT_wind007的博客-CSDN博客

自帶的HeidiSQL工具覺得界面不太友好,於是自己下載了一個Navicat進行操作,相關操作參照以下連接文檔:

Navicat使用快速入門教程_苜苜的爛筆頭的博客-CSDN博客_navicat使用教程詳解

 

以上步驟完成以后,打開C#工程,C#工程中的“引用”——添加——擴展——勾選MySql.Data,確認即可使用

在需要使用數據庫操作的文件頭添加  using MySql.Data.MySqlClient;

即可調用相關操作。

1、數據庫連接

 1         public bool ConnectToSql()
 2         {
 3 
 4             // 對象轉字符串方法
 5             MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder();
 6             builder.Database = "plc_control";   // 數據庫名
 7             builder.Server = "localhost";     // IP
 8             builder.Port = 3306;                // 端口號
 9             builder.UserID = "root";            // 用戶名
10             builder.Password = "root";          // 密碼
11             builder.CharacterSet = "utf8mb4";   // 編碼格式
12 
13             if (null == conn)
14             {
15                 conn = new MySqlConnection(builder.ToString());
16             }
17 
18             try
19             {
20                 conn.Open();
21 
22                 //在open之后調用就可以避免creatTable報錯
23                 MySqlCommand setcmd = new MySqlCommand("SET character_set_results=utf8mb4", conn);
24                 int n = setcmd.ExecuteNonQuery();
25                 setcmd.Dispose();
26 
27                 Console.WriteLine("連接成功!!!");
28 
29                 return true;
30             }
31             catch (Exception e1)
32             {
33                 Console.WriteLine("打印拋出:" + e1.ToString() + builder.ToString());
34                 return false;
35             }
36         }

 

2、數據庫關閉

 1     public void CloseConn()
 2         {
 3             if (null != conn)
 4             {
 5                 if (conn.State == ConnectionState.Open)
 6                 {
 7                     conn.Close();
 8                     Console.WriteLine("正常關閉!!!");
 9                 }
10             }
11         }

 

3、創建(create table)

 1         private void CreatActionLogTable()
 2         {
 3             string strCreat = string.Format(@"CREATE TABLE IF NOT EXISTS actionlog(
 4                                   `time` datetime DEFAULT NULL,
 5                                   `user` varchar(24) DEFAULT NULL,
 6                                   `log` varchar(200) DEFAULT NULL
 7                                 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE utf8mb4_unicode_ci;");
 8 
 9             ExecuteQuery(strCreat);
10         }
11 
12 
13      private void ExecuteQuery(string strCreat)
14         {
15             try
16             {
17                 MySqlCommand myCmd = new MySqlCommand(strCreat, conn);
18                 myCmd.ExecuteNonQuery();
19             }
20             catch (MySqlException ex) {
21                 Console.WriteLine("err:"+ex.Message);
22             }
23         }

 

4、增(insert)數據的批處理操作

 1      //插入指令的批處理操作
 2         public void ExecuteSqlTranssaction(List<string> sqlStrList)
 3         {
 4             //創建執行命令的command對象
 5             MySqlCommand command = new MySqlCommand();
 6             command.Connection = conn;
 7 
 8             //開啟mysql事務
 9             MySqlTransaction transaction = conn.BeginTransaction();
10             command.Transaction = transaction;
11 
12             try
13             {
14 
15                 if (sqlStrList.Count > 1)
16                 {
17                     for (int i = 0; i < sqlStrList.Count; i++)
18                     {
19                         string sqlStr = sqlStrList[i].ToString();
20                         if (sqlStr.Trim().Length > 1)
21                         {
22                             command.CommandText = sqlStr;
23                             command.ExecuteNonQuery();
24                         }
25 
26                         if (i > 0 && (i % 500 == 0
27                             || i == sqlStrList.Count - 1))
28                         {
29                             transaction.Commit();
30 
31                             if (i != sqlStrList.Count - 1)
32                             {
33                                 transaction = conn.BeginTransaction();
34                             }
35                         }
36                     }
37                 }
38                 else
39                 {
40                     for (int i = 0; i < sqlStrList.Count; i++)
41                     {
42                         string sqlStr = sqlStrList[i].ToString();
43                         if (sqlStr.Trim().Length > 1)
44                         {
45                             command.CommandText = sqlStr;
46                             command.ExecuteNonQuery();
47 
48                             transaction.Commit();
49 
50                         }
51                     }
52                 }
53             }
54             catch (MySqlException err)
55             {
56 
57                 Console.WriteLine("ExecuteSqlTranssaction error!!!" + err.ToString());
58 
59                 transaction.Rollback();
60                 throw new Exception(err.Message);
61 
62             }
63         }
64 
65         private void Insert2actionlog(C_ActionLog tmpActionLog)
66         {
67             string sqlStr = string.Format("insert into actionlog (time,user,log) " +
68                            "values('{0}','{1}','{2}');",
69                            tmpActionLog.dateTime,
70                            tmpActionLog.user,
71                            tmpActionLog.logInfo);
72 
73             Console.WriteLine(sqlStr);
74 
75             actSqlStrList.Add(sqlStr);
76         }

5、刪(delete) 整理碎片

 1     //多條刪除
 2         public int DeleteLog(DateTime sTime, DateTime endTime) {
 3 
 4             string startTimeStr = sTime.ToString();
 5             string endTimeStr = endTime.ToString();
 6 
 7             //需要挑選日期 
 8             string sqlStr = string.Format("DELETE FROM actionlog WHERE time BETWEEN '{0}' AND '{1}' LIMIT 10000;", startTimeStr, endTimeStr);
 9 
10             ExecuteQuery(sqlStr);
11 
12             //刪除數據以后,整理碎片  大量數據才需要用到
13             string alterStr = string.Format("alter table actionlog engine = innodb,ALGORITHM=INPLACE, LOCK=NONE;");
14             ExecuteQuery(alterStr);
15 
16             return 0;
17         }

6、查(select)

 1         //獲取日志
 2         public void SelectLogFromSql(short timeFlag, DateTime sTime, DateTime eTime, out List<C_ActionLog> logList)
 3         {
 4 
 5             logList = new List<C_ActionLog>();
 6 
 7             string sqlStr = "SELECT * FROM actionlog ";
 8             string timeStr = "";
 9             string endStr = ";";
10             string startTimeStr = sTime.ToString();
11             string endTimeStr = eTime.ToString();
12             if (1 == timeFlag)
13             {//需要挑選日期 
14                 timeStr = string.Format("WHERE time BETWEEN '{0}' AND '{1}' ", startTimeStr, endTimeStr);
15 
16             }
17 
18             sqlStr += timeStr + endStr;
19 
20             Console.WriteLine(sqlStr);
21 
22             MySqlCommand command = new MySqlCommand(sqlStr, conn);
23             MySqlDataReader reader = command.ExecuteReader();
24 
25             while (reader.Read())
26             {
27                 C_ActionLog ectionLog = new C_ActionLog();
28 
29                 ectionLog.dateTime = reader.GetDateTime("time");
30                 ectionLog.user = reader.GetString("user");
31                 ectionLog.logInfo = reader.GetString("log");
32 
33                 logList.Add(ectionLog);
34             }
35 
36             reader.Close();
37         }

7、改(Update)

1   updateStr = string.Format("UPDATE equipcraftconf SET id={0},craftName='{1}' WHERE staNo={2} AND craftNo={3};",
2                     equipCraftConf.id,
3                     equipCraftConf.craftInfo.craftName,
4                     equipCraftConf.craftInfo.staNo,
5                     equipCraftConf.craftInfo.craftNo          
6                     );
7 
8  ExecuteQuery(updateStr);

 


免責聲明!

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



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