C# 如何在增加ID列的情况下向sqlite表中插入多条记录
我想在sqlite数据库中插入一个视图记录。以下是我到目前为止的情况。这不起作用,数据库被锁定 如何从表中获取最大id,然后在增加id的同时插入一些记录 首先,我想获得表的最大id:C# 如何在增加ID列的情况下向sqlite表中插入多条记录,c#,C#,我想在sqlite数据库中插入一个视图记录。以下是我到目前为止的情况。这不起作用,数据库被锁定 如何从表中获取最大id,然后在增加id的同时插入一些记录 首先,我想获得表的最大id: private void button_voeg_gebuiker_toe_Click(object sender, EventArgs exp) { try {//Hoogste ID bepalen if (getM
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...
}
}
你能分享一下你的表格结构吗。。 当您检索Max id时,您会说您的数据库被锁定,因此您可以使用SHARED lock,这将在执行第一个SELECT语句时获得。共享锁意味着数据库可以读取,但不能写入。当执行第一个INSERT、UPDATE或DELETE语句时,将获得保留锁。
有关sqlite no lock的更多信息,请参考此链接-如果
ID
列是主键
,则可以插入数据,而无需ID
列<代码>插入用户(GEBRUIKER、WACHTWOORD、ROL)。。。SQLite将增加ID本身。@Wudge:我认为您混淆了主键和标识。@Zohar Peled:SQLite将定义为整数主键的列作为标识列处理。不需要像在MS SQL Server中那样使用AUTOINCREMENT
。@Wudge谢谢,我学到了一些新东西。我找到了。读卡器必须关闭。首先使用getmaxid,然后使用select查询。当我在getmaxid中关闭读卡器,然后使用select查询时,就不再有数据库锁了。