“使用DataSet做中间缓存,提高数据库操作效率”
如下所示,c#项目中使用sqlite数据库,如果使用command命令进行增、删、改...操作数据,编程工作量大,且效率较低。
//连接到数据库并打开
string connectionString = "data source=" + @"E:\数据库\student.db";//地址
SQLiteConnection connection = new SQLiteConnection(connectionString);//连接
connection.Open(); //打开
string sql = "";
//删除所有数据
sql = "delete from user";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
//添加数据1
sql = "insert into user(id,name,passward) values (1,\"s\",\"sec\")";
command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
//修改数据
sql = "update user set name = '" + name + "' , passward = '" + pass + "' where id =" + id;
SQLiteCommand command1 = new SQLiteCommand(sql, connection);
command1.ExecuteNonQuery();
...
针对这个问题,这里介绍使用DataSet缓存的方式,提高工作效率,降低难度。
将数据库中的 部分数据读取到DataSet,然后,可以当做本地数据库,进行数据操作。修改完毕,再将数据同步到数据库。对于数据库,只需要执行读取、导入操作,大大提高了操作效率。
下面,使用一段代码进行说明。
//1.主程序
//批量处理数据
private void button5_Click(object sender, EventArgs e)
{
//连接到数据库并打开
string connectionString = "data source=" + @"E:\student.db";//地址
SQLiteConnection connection = new SQLiteConnection(connectionString);//连接
connection.Open(); //打开
string sql = "";
//查询
string SQLString = "select * from user"; //sql语句
SQLiteDataAdapter command1 = new SQLiteDataAdapter(SQLString, connection);
//读取数据
DataSet ds = new DataSet();
command1.Fill(ds, "user");
//批量添加数据
string[,] arr = new string[1000, 3];
int num = InPutCsvData("D:\user.csv", arr);
string[] array = new string[3];
for (int i = 0; i < num; i++)
{
array[0] = arr[i, 0];
array[1] = arr[i, 1];
array[2] = arr[i, 2];
AddDataToDataset(ref ds, "user", array);
}
//把datable数据批量导入sqlite数据库,生成对应命令
SQLiteCommandBuilder src = new SQLiteCommandBuilder(command1);
//更新数据库表格
command1.Update(ds, "user");
this.dataGridView1.DataSource = ds.Tables[0];
connection.Close();
}
//1.1 导入本地csv格式表格数据
public int InPutCsvData(string path, string[,] array)
{
try
{
int num_line = 0;
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
string line;
while ((line = sr.ReadLine()) != null)// 从文件读取并显示行,直到文件的末尾
{
string[] arr = line.Split(',');
for (int i = 0; i < 3; i++)
array[num_line, i] = arr[i];
num_line = num_line + 1;
}
return num_line;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return 0;
}
//1.2添加数据到Dataset
public void AddDataToDataset(ref DataSet dt,string tablename,string[] arr)
{
DataRow r= dt.Tables[tablename].NewRow();;
for (int i = 0; i < arr.Count(); i++)
{
r[i] = arr[i];
}
dt.Tables[tablename].Rows.Add(r);
}