sqlite 自动更新db
string database = AppDomain.CurrentDomain.BaseDirectory + "\\DalianStore.db"; string connectionString = @"Data Source=" + Path.GetFullPath(database); string commandText = @"SELECT * FROM Items ORDER BY payTime"; DBHelper helper = new DBHelper(connectionString); if (helper.LoadData(commandText, "") == true) { dataGridViewOrderList.DataSource = helper.DataSet.Tables[0]; } //更新数据库 private void dataGridViewOrderList_CellValidated(object sender, DataGridViewCellEventArgs e) { //如果改行有值发生改变 if (dataGridViewOrderList.IsCurrentRowDirty) { DialogResult ret = MessageBox.Show("确定要更改数据吗?", "系统提示",MessageBoxButtons.OKCancel); if (ret == DialogResult.OK) { if (helper != null) { helper.Save(); } } }//end of out if }
DBHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SQLite; using System.Data; namespace MyStore { class DBHelper { #region 变量 private SQLiteConnection _connection = null; private string _connectionString = ""; private SQLiteDataAdapter _dataAdapter = null; private DataSet _dataSet = null; private string _fieldNameID = ""; // The DataSet is filled with the methode LoadDataSet public DataSet DataSet { get { return _dataSet; } } #endregion #region 构造函数 public DBHelper(string connectionString) { _connectionString = connectionString; } #endregion public bool LoadData(string commandText, string opt) { bool ret = true; _fieldNameID = opt; try { _connection = new SQLiteConnection(_connectionString); _connection.Open(); _dataAdapter = new SQLiteDataAdapter(commandText, _connection); _dataAdapter.RowUpdated += dataAdapter_RowUpdated; _dataSet = new DataSet(); SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(_dataAdapter); _dataAdapter.InsertCommand = commandBuilder.GetInsertCommand(); _dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand(); _dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand(); _dataAdapter.Fill(_dataSet); return true; } catch (SQLiteException) { ret = false; } finally { _connection.Close(); } return ret; } public bool Load(string commandString) { return LoadData(commandString,""); } public bool Save() { bool ret = true; try { _connection.Open(); _dataAdapter.Update(_dataSet); ret = true; } catch (SQLiteException) { ret = false; } finally { _connection.Close(); } return ret; } //在这个事件里面做一些特别的判断 void dataAdapter_RowUpdated(object sender, System.Data.Common.RowUpdatedEventArgs e) { } } }
作者:ohmytime
出处:http://www.cnblogs.com/ohmytime/
若标题中有“转载”字样,则本文版权归原作者所有。若无转载字样,本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
浙公网安备 33010602011771号