C#操作Sqlite輕量級數據庫實現增刪改查
寫這篇文章是因為一位坑逼同事,整天問我怎么操作數據庫,不就是增刪改查嗎,有什么困難嗎?我個人覺得他是因為懶。算了就當是豐富筆記了,順便解決一天的文章更新。C#操作Sqlite數據庫很簡單,因為Sqlite提供了C#的支持庫,只需要引入dll動態鏈接庫,我們就能像操作mysql一樣操作Sqlite。下面是C#操作Sqlite輕量級數據庫實現增刪改查的全過程,一起學習下吧。
Sqlite下載地址:http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
可視化工具下載地址:https://sqlitestudio.pl/index.rvt?act=download
雖然下載下來是EXE可執行文件,但是我們只需要里面的System.Data.SQLite.dll文件而已,安裝過程只是解壓,放心安裝。
解壓好后,通過VS引入里面的System.Data.SQLite.dll文件,然后在你的項目中使用using System.Data.SQLite
進行引用。
C#操作Sqlite
首先聲明全局變量:
SQLiteConnection Conn;
創建數據庫
string FilePath = Application.StartupPath + "\\" + textBox1.Text + ".db"; if (!File.Exists(FilePath)) { SQLiteConnection.CreateFile(FilePath); } try { Conn = new SQLiteConnection("Data Source=" + FilePath + ";Version=3;"); Conn.Open(); } catch (Exception ex) { throw new Exception("打開數據庫:" + FilePath + "的連接失敗:" + ex.Message); }
textBox1是數據庫名稱。
創建數據表
try { string sql = "create table " + textBox2.Text + " (name varchar(20), score int)"; SQLiteCommand command = new SQLiteCommand(sql, Conn); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("創建數據表" + textBox2.Text + "失敗:" + ex.Message); }
textBox2是數據表名稱,Conn是數據庫連接,前面設置的全局變量。
增加數據
try { string sql = "insert into " + textBox2.Text + " (name, score) values ('" + textBox3.Text + "', " + Convert.ToInt32(textBox4.Text) + ")"; SQLiteCommand command = new SQLiteCommand(sql, Conn); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("插入數據:" + textBox3.Text + ":" + textBox4.Text + "失敗:" + ex.Message); }
這里的增加數據與數據表的數據結構需要一一對應,不懂的自己去學習下sql語句。
刪除數據
try { string sql = "delete from " + textBox2.Text + " where " + textBox6.Text + "='" + textBox7.Text + "'"; SQLiteCommand command = new SQLiteCommand(sql, Conn); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("刪除數據:" + textBox6.Text + ":" + textBox7.Text + "失敗:" + ex.Message); }
同樣是使用數據庫連接,進行sql查詢。
修改數據
try { string sql = "update " + textBox2.Text + " set score = " + Convert.ToInt32(textBox9.Text) + " where name='" + textBox8.Text + "'"; SQLiteCommand command = new SQLiteCommand(sql, Conn); command.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("更新數據:" + textBox8.Text + ":" + textBox9.Text + "失敗:" + ex.Message); }
查詢數據
try { string sql = "select * from " + textBox2.Text + " order by score desc"; SQLiteCommand command = new SQLiteCommand(sql, Conn); SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()){ textBox5.Text = "Name: " + reader["name"] + "\tScore: " + reader["score"] + "\r\n" + textBox5.Text; } } catch (Exception ex) { throw new Exception("查詢數據失敗:" + ex.Message); }