SQLite 数据库未打开错误
Posted
技术标签:
【中文标题】SQLite 数据库未打开错误【英文标题】:SQLite Database is not open Error 【发布时间】:2015-08-08 16:27:29 【问题描述】:我有一个构造函数,它从 SQL Server 数据库中获取数据并将其放入本地 SQLite 数据库中:
public ForemanController()
connectionString.DataSource = "dxdb02v";
connectionString.InitialCatalog = "QTRAX4619410";
connectionString.UserID = "tunnelld";
connectionString.Password = "david";
string queryString = "SELECT * FROM [QTRAXAdmin].[vwQT_Foreman]";
List<Foreman> list;
// Creates a SQL connection
using (var connection = new SqlConnection(connectionString.ToString()))
using (var command = new SqlCommand(queryString, connection))
connection.Open();
using (var reader = command.ExecuteReader())
list = new List<Foreman>();
while (reader.Read())
list.Add(new Foreman ForeBadge = reader.GetString(0), ForeName = reader.GetString(1) );
connection.Close();
allForeman = list.ToArray();
string deleteSQL = "DELETE FROM Foreman;";
using (SQLiteConnection SQLconn1 = new SQLiteConnection(SQLiteConnectionString))
using (var command = new SQLiteCommand(deleteSQL, SQLconn1))
command.Connection.Open();
command.ExecuteNonQuery();
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (@param1, @param2);";
cmd2.Parameters.Add(new SQLiteParameter("@param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("@param2", row.ForeName));
cmd2.ExecuteNonQuery();
在最后一个 using 语句之前一切似乎都运行良好:
using (SQLiteConnection SQLconn2 = new SQLiteConnection(SQLiteConnectionString))
SQLiteCommand cmd2 = SQLconn2.CreateCommand();
foreach (Foreman row in allForeman)
cmd2.CommandText = "INSERT INTO Foreman (ForeBadge, ForeName) VALUES (@param1, @param2);";
cmd2.Parameters.Add(new SQLiteParameter("@param1", row.ForeBadge));
cmd2.Parameters.Add(new SQLiteParameter("@param2", row.ForeName));
cmd2.ExecuteNonQuery();
我收到此错误:
【问题讨论】:
很明显,您不会像打开其他人那样打开它。你需要一个SQLconn2.Open()
或cmd2.Connection.Open()
在某个地方。
缺少SQLConn2.Open();
旁注 - 在类构造函数中做的太多了。我会认真重新考虑将其作为一个单独的方法(或一组方法)。构造函数应该是轻量级的并且不应该抛出任何异常(因为它们更难调试)
【参考方案1】:
那是因为那是您忘记打开连接的唯一地方。
添加这个:SQLconn2.Open();
【讨论】:
这可能很明显,但为什么我不需要为 DELETE 语句打开连接? 你打开它是为了 DELETE 语句:command.Connection.Open();
【参考方案2】:
你忘记打开连接了。
SQLConn2.Open();
【讨论】:
以上是关于SQLite 数据库未打开错误的主要内容,如果未能解决你的问题,请参考以下文章
错误 java.sql.SQLException:从数据库中检索 Blob(图像)时 SQLite JDBC 驱动程序未实现