我有一个用 C# 编写的简单程序,我正在使用 SQLite 保存配置文件列表(电子邮件、密码)。一切正常,直到我关闭程序然后重新打开它。当我这样做时, table 是空的。这段代码位于我的表单构造函数中,它在程序加载时首先触发(这是一个单一的表单程序,非常基本)。我正在使用 System.Data.SQLite 库。我可以在我的项目文件夹 (bin/debug/..) 中看到该文件。任何人都可以解释为什么这些信息没有被保存并且在重新打开程序时无法阅读吗?
SQLiteConnection.CreateFile("MyDatabase.db");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.db;Version=3;");
m_dbConnection.Open();
string sql = "CREATE TABLE " + profileTable + " (" + emailCol + " VARCHAR(320), " + passwordCol + " VARCHAR(30))";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "SELECT * FROM "+profileTable+" order by "+emailCol+" desc";
command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
emailProfileListBox.Items.Add(reader[emailCol] as String);
}
这是我的 INSERT 语句,它确实插入并已通过验证。
string sql1 = "INSERT INTO "+profileTable+" ("+emailCol+", "+passwordCol+") VALUES (\'"+from_email_address.Text+"\', \'"+passwordTextBox.Text+"\')";
SQLiteCommand command1 = new SQLiteCommand(sql1, m_dbConnection);
command1.ExecuteNonQuery();
最佳答案
第一行,如果每次运行时都创建一个新文件,该文件将被覆盖。
SQLiteConnection.CreateFile("MyDatabase.db");
将创建语句包装在 if
block 中,而不是检查文件是否存在于磁盘上。
if (!System.IO.File.Exists("MyDatabase.db"))
{
SQLiteConnection.CreateFile("MyDatabase.db");
// continue your creation script here
}
Creates or overwrites a database file in the specified path. This just creates a zero-byte file which SQLite will turn into a database when the file is opened properly. Note that an existing file will be overwritten.
旁注
- 您还应该在
using
block 中包装您的连接和类型实现IDisposable
的任何其他实例,以确保始终释放外部资源。 - 您应该对传递给它们的任何值使用参数化语句。因此,您的选择中的插入、更新和条件应该使用参数来传递值。
- 永远不要存储密码,即使是加密的密码。改为创建密码的单向加盐哈希并存储它。有很多现有的库/代码片段可以为您完成这项工作。
关于重新打开程序后 c# sqlite 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282894/