【发布时间】:2020-02-18 04:37:20
【问题描述】:
我正在尝试使用 C# 和 sqlite 编辑此表中的插入。
SQLite 表:
CREATE TABLE "utenti" (
"id" INTEGER NOT NULL,
"grado" TEXT,
"cognome" TEXT NOT NULL,
"nome" TEXT NOT NULL,
"codice_fiscale" TEXT
)
CREATE TABLE "entrate" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"id_utente" INTEGER NOT NULL,
"nome" TEXT NOT NULL,
"entrata" TEXT NOT NULL,
"uscita" TEXT
);
我想确保首先我们去检查文本框中是否有插入“id_utente”的记录。 如果存在且“uscita”列的值为空,则更新该行并在“uscita”列中添加值。 如果文本框中没有插入“id_utente”的行,或者存在但输入了“entrata”和“uscita”列值,则插入一条新记录。
测试代码:
public static bool SavePerson(int idUtente, string nome, string orario)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
var output = cnn.Query($"select * from utenti where id = {idUtente}").FirstOrDefault();
if (output != null) {
nome = FindCognome(idUtente);
string query;
query = $"IF NOT EXISTS(SELECT (id_utente, nome, entrata) FROM entrate WHERE id_utente = '\"{idUtente}\"')" +
$"BEGIN"
$"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")" +
$"END" +
$"ELSE" +
$"BEGIN" +
$"UPDATE entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\") WHERE id_utente = '\"{idUtente}\"')" +
$"END";
//cnn.Execute($"INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")");
cnn.Execute(query);
cnn.Close();
return true;
}
else return false;
}
}
我已经进行了各种测试和各种尝试,但对于表格中行的控制变量,我发现自己遇到了困难。
其他错误测试
query = $"UPDATE entrate SET uscita = \"{orario}\"," +
$"CASE WHEN id_utente = {idUtente}" +
$"ELSE INSERT INTO entrate (id_utente, nome, entrata) VALUES (\"{idUtente}\",\"{nome}\",\"{orario}\")";
【问题讨论】:
-
如果您使用的是 SQLite,请使用 SQLite 预期的 SQL 语法。 sqlitetutorial.net/sqlite-exists