当前位置:Gxlcms > 数据库问题 > Sqlite创建增删改查

Sqlite创建增删改查

时间:2021-07-01 10:21:17 帮助过:2人阅读

System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SQLite; using System.Data.Common; using System.IO; namespace SqliteDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string sqlitePath = Application.StartupPath + "/test.db"; System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection(); System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(); string sql; /// <summary> /// 创建数据库 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreat_Click(object sender, EventArgs e) { if (File.Exists(sqlitePath)) { MessageBox.Show("数据库已经存在","error",MessageBoxButtons.OK,MessageBoxIcon.Error); } else { try { //创建一个数据库文件 System.Data.SQLite.SQLiteConnection.CreateFile(sqlitePath); } catch (Exception ex) { MessageBox.Show("创建数据库失败" + ex.ToString()); } } } private void btnConnect_Click(object sender, EventArgs e) { //连接数据库 try{ System.Data.SQLite.SQLiteConnectionStringBuilder connstr = new System.Data.SQLite.SQLiteConnectionStringBuilder(); connstr.DataSource = sqlitePath; //connstr.Password = "admin";//设置密码,SQLite ADO.NET实现了数据库密码保护 conn.ConnectionString = connstr.ToString(); conn.Open(); cmd.Connection = conn; } catch (Exception ex) { MessageBox.Show("连接数据库" + ex.ToString()); } } private void btnCreatTable_Click(object sender, EventArgs e) { try { //创建表 sql = "CREATE TABLE test(username varchar(20),password varchar(20))"; cmd.CommandText = sql; cmd.Connection = conn; cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show("创建表失败" + ex.ToString()); } } private void btnAdd_Click(object sender, EventArgs e) { try { sql = "insert into test (username,password) values (‘" + "123" + "‘,‘" + "456" + "‘)"; cmd.CommandText = sql; cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show("增加失败" + ex.ToString()); } } private void btnSelect_Click(object sender, EventArgs e) { try { listView1.Items.Clear(); sql = "SELECT * FROM test"; cmd.CommandText = sql; System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { ListViewItem lvi = new ListViewItem(); lvi.Text = (listView1.Items.Count + 1).ToString(); lvi.SubItems.Add(reader.GetString(0)); lvi.SubItems.Add(reader.GetString(1)); listView1.Items.Add(lvi); } reader.Close(); } catch (Exception ex) { MessageBox.Show("读取失败" + ex.ToString()); } } private void btnDeleteAll_Click(object sender, EventArgs e) { sql = "delete FROM test"; cmd.CommandText = sql; cmd.ExecuteNonQuery(); } private void btnDelete_Click(object sender, EventArgs e) { sql = "DELETE FROM test WHERE username = ‘"+textBox1.Text.Trim()+""; cmd.CommandText = sql; cmd.ExecuteNonQuery(); } } }

 

Sqlite创建增删改查

标签:

人气教程排行