2019年12月15日 星期日

用C#連結MYSQL做操作

安裝好MYSQL套件後
using MySql.Data.MySqlClient;

要先登入MYSQL,為了讓未來如果要修改簡單點,所以設變數

            string dbHost = "192.168.0.1";//資料庫位址
            string dbUser = "userName";//資料庫使用者帳號
            string dbPass = "Password";//資料庫使用者密碼
            string dbName; //資料庫名稱
            String cmdText; //要輸入的指令

            string connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            MySqlConnection conn = new MySqlConnection(connStr);
            conn.Open();




1.查詢 SELECT (要輸出的欄位,全部則用*)
   從資料庫的哪個表單  FROM
   篩選的條件 WHERE

例如:
cmdText = "SELECT * FROM city WHERE " + Keyword +" = '" + KeyText + "'";

2.篩選條件可以使用%來做包含

例如:
cmdText = "SELECT * FROM city WHERE " + Keyword +" like '%" + KeyText + "%' ";

前後都加代表你輸入查詢的字前或後包含就行
例如輸入001就會出現A001或001A之類的,使用=只會查詢到001無法查詢到001A

3.後面使用limit可以限制搜尋的筆數上限,可以請使用者把條件設定的更精確點

例如:
cmdText = "SELECT * FROM city WHERE " + Keyword +" like '%" + KeyText + "%' limit 50";

這樣最多只會搜尋到符合條件的50筆

4.刪除資料 使用DELELE

前面先宣告個
                MySqlCommand command = conn.CreateCommand();

                    command.CommandText = "Delete from city where ID = '" + ID + "'";
                    command.ExecuteNonQuery();

這樣就會把ID符合的資料刪除

5.新增資料 使用INSERT

                    command.CommandText = "Insert into city(ID,Name) values ('" + ID + "','" + Name + "')";
                    command.ExecuteNonQuery();

這樣把ID和NAME的值賦予進去

6.修改資料 使用UPDATE

                    command.CommandText = "update city SET Name = " + Name + "' WHERE ID = '" + ID + "'";
                    command.ExecuteNonQuery();

這樣把ID相符資料中的NAME改掉

沒有留言:

張貼留言