我想在sqlite数据库中插入视图记录。以下是我到目前为止的情况。这不起作用,数据库被锁定 如何从表中获取最大ID,然后在增加id时插入几条记录?
首先我想获得表中的最大ID:
private void button_voeg_gebuiker_toe_Click(object sender, EventArgs exp)
{
try
{//Hoogste ID bepalen
if (getMaxID() >= -1)
{
insertIntoUsers(); //insert mag starten
}
else
{
//logging...
}
}
catch (Exception e)
{
//logging...
}
}
getMaxId功能:
public int getMaxID()
{
try
{
connectToDatabase();
string sql = "select max(ID) as ID from USERS";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
id = reader.GetInt32(0);
id += 1;
m_dbConnection.Close();
return id;
}
}
catch (Exception e)
{
string fout = e.ToString(); //bad solution
id = 1;
return id; //if table is emtpy then return id=1
}
return -1;
}
catch (Exception e)
{
//logging...
m_dbConnection.Close();
return -1;
}
}
private void connectToDatabase()
{
Class_check_app_environment locatieDB = new Class_check_app_environment();
try
{
m_dbConnection = new SQLiteConnection("Data Source=" + locatieDB.Get_Applicatiepad() + Form_Main.DataMap + Form_Main.GebruikersDatabase + ";" + Form_Main.SqliteVersie + ";");
m_dbConnection.Open();
}
catch (Exception e)
{
//
}
}
插入功能:
private void insertIntoUsers()
{
try
{
m_dbConnection.Open();
string sql = "insert into USERS (ID, GEBRUIKER, WACHTWOORD, ROL) values (@ID, @GEBRUIKERNAAM, @WACHTWOORD, @ROL)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.Parameters.Add(new SQLiteParameter("@ID", id));
command.Parameters.Add(new SQLiteParameter("@GEBRUIKERNAAM", gebruikernaam));
command.Parameters.Add(new SQLiteParameter("@WACHTWOORD", wachtwoord));
command.Parameters.Add(new SQLiteParameter("@ROL", rol));
command.ExecuteNonQuery();
m_dbConnection.Close(); //connectie weer sluiten
}
catch (Exception e)
{
//logging...
}
}
答案 0 :(得分:0)
请您分享您的表格结构以获得更多说明。 你说你的数据库在检索Max id时被锁定,为此你可以在执行第一个SELECT语句时获得SHARED锁。共享锁意味着可以读取数据库但不能写入数据库。执行第一个INSERT,UPDATE或DELETE语句时将获取RESERVED锁。 您可以参考此链接以获取有关sqlite无锁的更多信息 - https://www.sqlite.org/lockingv3.html