另外,还要请教,虽然方案1直接被客户否决了
因为我之前没用过SQLite,还是想测试下,是否支持多个Connection
本以为下面测试代码应该行得通,结果报错为:SQLite Error 5: 'database is locked
(可以确保其他程序没有使用的)
也请教下这样的原因:
[C#] 纯文本查看 复制代码 using Microsoft.Data.Sqlite;
namespace TestDB
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
SqliteConnection connectionForSelect = new SqliteConnection(@"DataSource=D:\111.db");
connectionForSelect.Open();
SqliteConnection connectionForTransaction = new SqliteConnection(@"DataSource=D:\111.db");
connectionForTransaction.Open();
/**
* 新建名为my_test_table的表格,它有一列为id,然后插入一行数据3
*/
SqliteCommand createTableCmd = connectionForSelect.CreateCommand();
createTableCmd.CommandText = "DROP TABLE IF EXISTS 'my_test_table'";
createTableCmd.ExecuteNonQuery();
createTableCmd.CommandText = "CREATE TABLE my_test_table(id integer primary key)";
createTableCmd.ExecuteNonQuery();
createTableCmd.CommandText = "INSERT INTO my_test_table(id) values(3)";
createTableCmd.ExecuteNonQuery();
SqliteCommand selectDataCmd = connectionForSelect.CreateCommand();
using (SqliteTransaction transaction = connectionForTransaction.BeginTransaction())
{
int currentId = 0;
while (true)
{
selectDataCmd.CommandText = $"SELECT * from my_test_table where id={currentId}";
SqliteDataReader reader = selectDataCmd.ExecuteReader();
if (reader.HasRows == true)
{
// 遇到已存在的,则停止,并提交事务
transaction.Commit();
reader.Close();
break;
}
else
{
// 没有则插入
SqliteCommand insertCmd = connectionForTransaction.CreateCommand();
insertCmd.Transaction = transaction;
insertCmd.CommandText = $"INSERT INTO my_test_table(id) values({currentId})";
insertCmd.ExecuteNonQuery();
}
reader.Close();
currentId++;
}
}
connectionForSelect.Close();
connectionForTransaction.Close();
SqliteConnection.ClearAllPools();
MessageBox.Show("完毕");
}
}
}
|