標籤:ogr lda 增刪改 項目 string data mysql 資料庫 pre style
該文講解 C# 對 mysql 資料庫進行增刪改查操作。
1. 安裝資料庫,注意要安裝 Connector NET。
2. 引入 MySql.Data.dll,添加項目引用,該檔案一般位置為:C:\Program Files (x86)\MySQL\Connector NET xx\Assemblies\v xx(由 mysql 安裝位置決定)。
3. 在 MySQL Workbench 中添加測試表,本例建立了一個資料庫 test,並在該資料庫中建立了一個 user 表,表中有 username 和 password 兩個表項,如下:
4. 對資料庫進行增刪改查,C# 代碼如下:
1 using System; 2 using MySql.Data.MySqlClient; 3 4 namespace MySQL資料庫操作 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 {10 // 資料庫配置11 string connStr = "Database=test;datasource=127.0.0.1;port=3306;user=root;pwd=root;";12 MySqlConnection conn = new MySqlConnection(connStr);13 14 conn.Open();15 16 #region 查詢17 // // 查詢user表中所有條目18 // MySqlCommand cmd = new MySqlCommand("select * from user", conn);19 //20 // MySqlDataReader reader = cmd.ExecuteReader();21 //22 // // 逐行讀取資料23 // while (reader.Read())24 // {25 // string username = reader.GetString("username");26 // string password = reader.GetString("password");27 // Console.WriteLine(username + ":" + password);28 // }29 //30 // reader.Close();31 #endregion32 33 #region 插入34 // // 正常插入一條資料35 // string username = "lj";string password = "6666";36 // MySqlCommand cmd = new MySqlCommand("insert into user set username =‘" + username + "‘" + ",password=‘" + password + "‘", conn);37 // cmd.ExecuteNonQuery();38 39 // // sql 注入,會刪除資料庫40 // string username = "lj"; string password = "6666‘; delete from user;";41 // MySqlCommand cmd = new MySqlCommand("insert into user set username =‘" + username + "‘" + ",password=‘" + password + "‘", conn);42 // cmd.ExecuteNonQuery();43 44 // // 防止注入,不會執行刪除資料庫語句45 // string username = "lj"; string password = "6666‘; delete from user;";46 // MySqlCommand cmd = new MySqlCommand("insert into user set [email protected] , password = @pwd", conn);47 // cmd.Parameters.AddWithValue("uid", username);48 // cmd.Parameters.AddWithValue("pwd", password);49 // cmd.ExecuteNonQuery();50 #endregion51 52 #region 刪除53 // // 刪除 id 為 6 的條目54 // MySqlCommand cmd = new MySqlCommand("delete from user where id = @id", conn);55 // cmd.Parameters.AddWithValue("id", 6);56 //57 // cmd.ExecuteNonQuery();58 #endregion59 60 #region 更新61 // 將 id 為 7 的條目 pwd 修改為 lll62 MySqlCommand cmd = new MySqlCommand("update user set password = @pwd where id = 7", conn);63 cmd.Parameters.AddWithValue("pwd", "lll");64 65 cmd.ExecuteNonQuery();66 #endregion67 68 conn.Close();69 70 Console.ReadKey();71 }72 }73 }
C# 操作mysql資料庫