1. 對數據庫增, 刪, 改
//數據庫文件存儲路徑,(Environment.CurrentDirectory:為當前工作目錄的完全路徑) string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db"; //創建連接數據庫實例,指定文件位置 SQLiteConnection con = new SQLiteConnection(dbPath); //打開數據庫,若文件不存在會自動創建 con.Open(); //建表語句 string sql = "CREATE TABLE IF NOT EXISTS student(id integer, name varchar(20), sex varchar(2));"; //創建sql執行指令對象 SQLiteCommand com = new SQLiteCommand(sql, con); //如果不帶參數時, 使用一下語句賦值 //com.CommandText = sql; //com.Connection = con; //執行sql指令創建建數據表,如果表不存在,創建數據表 com.ExecuteNonQuery(); //給表添加數據 //1. 使用sql語句逐行添加 com.CommandText = "INSERT INTO student VALUES(1, '小紅', '男')"; com.ExecuteNonQuery(); com.CommandText = "INSERT INTO student VALUES(2, '小李', '女')"; com.ExecuteNonQuery(); com.CommandText = "INSERT INTO student VALUES(3, '小明', '男')"; com.ExecuteNonQuery(); //2. 使用事務添加 //實例化一個事務對象 SQLiteTransaction tran = con.BeginTransaction(); //把事務對象賦值給com的transaction屬性 com.Transaction = tran; //設置帶參數sql語句 com.CommandText = "INSERT INTO student VALUES(@id, @name, @sex)"; for (int i = 0; i < 10; i++) { //添加參數 com.Parameters.AddRange(new[] {//添加參數 new SQLiteParameter("@id", i + 1), new SQLiteParameter("@name", "test" + i), new SQLiteParameter("@sex", i % 3 == 0 ? "男" : "女") }); //執行添加 com.ExecuteNonQuery(); } //提交事務 tran.Commit(); //關閉數據庫 con.Close();
2. 讀取數據
//數據庫路徑 string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db"; //創建數據庫實例,指定文件位置 SQLiteConnection conn = new SQLiteConnection(dbPath); //打開數據庫,若文件不存在會自動創建 conn.Open(); //查詢sql語句 string sql = "select * from student"; //實例化sql指令對象 SQLiteCommand cmdQ = new SQLiteCommand(sql, conn); //存放讀取數值 SQLiteDataReader reader = cmdQ.ExecuteReader(); //顯示數據的控件 richTextBox1.Text = ""; //讀取每一行數據 while (reader.Read()) { //讀取並賦值給控件 richTextBox1.Text += reader.GetInt32(0) + " " + reader.GetString(1) + " " + reader.GetString(2) + "\n"; } //關閉數據庫 conn.Close();