说到使用数据库的话,无非也就是对数据的增加,删除和修改以及查询。前文已经
创建好了程序,现在我们就可以来具体实现Sqlite的数据操作,增删改查。
第一步,创建连接字符串来连接数据库:
private void lianjie(){}//重新写个方法,将代码写在里面,然后放到窗体加载事件中,
因为是窗体起始要显示的数据。增删改查则要写在按钮的点击事件里面。
string Sqlite= @"C:/Users/Administrator/Desktop/SQLlite/yy.db";数据表的路径 SQLiteConnection con = new SQLiteConnection("data source="+Sqlite); con.Open();
第二步,创建命令对象执行SQL语句:
SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = con; cmd.CommandType = CommandType.Text; if (textBox6.Text!="") { cmd.CommandText = "select * from User where Name like ‘%"+textBox6.Text+"%‘";//查询输入 } else { cmd.CommandText = "select * from User";//查询所有 }
第三步,将数据绑定到Bindingsource。
//数据源和数据集的交换 SQLiteDataAdapter da = new SQLiteDataAdapter(); DataSet dt = new DataSet(); da.SelectCommand = cmd; da.Fill(dt); //将数据绑定bindingsource bindingSource1.DataSource = dt.Tables[0]; //将bindingsource中的值赋给GridView dataGridView1.DataSource = bindingSource1; //关闭连接 con.Close();
第四步,文本框获取值。Clear()清除值。(这个写到窗体加载中)
this.textBox1.Clear(); this.textBox1.DataBindings.Add("Text", bindingSource1, "Id"); this.textBox2.Clear(); this.textBox2.DataBindings.Add("Text",bindingSource1,"Name"); this.textBox3.Clear(); this.textBox3.DataBindings.Add("Text", bindingSource1, "Sex"); this.textBox4.Clear(); this.textBox4.DataBindings.Add("Text", bindingSource1, "Class"); this.textBox5.Clear(); this.textBox5.DataBindings.Add("Text",bindingSource1,"Number");
第五步,增删改,写在不同的点击事件中。同样的创建连接,创建命令。(SQL语句不同)
string sqlite = @"C:/Users/Administrator/Desktop/SQLlite/yy.db";数据表的路径 SQLiteConnection con = new SQLiteConnection("data source=" + sqlite); con.Open(); string sql = "delete from User where Number=‘" + textBox5.Text + "‘"; SQLiteCommand com = new SQLiteCommand(sql,con); com.Connection = con; int rows = com.ExecuteNonQuery(); MessageBox.Show("删除成功!"+rows+"行"); con.Close();关闭 lianjie(); //刷新数据调用查询方法
最后,完成!??
原文:https://www.cnblogs.com/Duck1/p/10996704.html