试图在统一上插入c#中的SQLite数据库
本文关键字:中的 SQLite 数据库 插入 | 更新日期: 2023-09-27 18:26:54
我目前正在做一项关于电梯的任务,最后一部分是建立一个数据库,记录电梯何时打开以及在哪个楼层。
在团结中,我得到了这个例外:
"InvalidOperationException:没有与此关联的连接命令"
完整项目的副本,如果你想看看。
https://onedrive.live.com/redir?resid=3F68EB193D2E3399!432&authkey=!AOGf1Et4si0a_k4&ithint=文件%2zip
这是我用来创建插入语句的代码
(很抱歉,如果评论让它变得一团糟,我会这么做,这样我就可以跟踪所有事情的进展)
void DataBase()
{
string currenttime = DateTime.Now.ToShortTimeString(); //sets currenttime variable to the current time
string currentdate = DateTime.Now.ToShortDateString(); //sets currentdate variable to the current date
int currentfloor = 0; //creates currentfloor variable
if (FG) //if FG is true
{
currentfloor = 1; //sets current floor to 0
}
else if (F1) //if F1 is true
{
currentfloor = 2; //sets current floor to 1
}
else if (F2) //if F2 is true
{
currentfloor = 3; //sets current floor to 2
}
IDbConnection dbconn;
string conn = "URI=file:" + Application.dataPath + "/lift_DB.s3db"; //Path to database.
dbconn = (IDbConnection)new SqliteConnection(conn); //creates database connection
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand(); //creates command on connection
string sqlInsert = "INSERT INTO lift_TB (Date,Time,Floor) VALUES (@currentdate,@currenttime,@currentfloor);"; // creates insert statement on sql insert string
SqliteCommand command = new SqliteCommand(); //creates new sqlite command
dbcmd.Parameters.Add(new SqliteParameter("@currentdate", currentdate)); //gives @currentdate sqlite parrameter data from current date variable
dbcmd.Parameters.Add(new SqliteParameter("@currenttime", currenttime)); //gives @currenttime sqlite parrameter data from current time variable
dbcmd.Parameters.Add(new SqliteParameter("@currentfloor", currentfloor)); //gives @currentfloor sqlite parrameter data from current floor variable
dbcmd.CommandText = sqlInsert; // sets dbcmd.CommandText to be equal to the insert statement created above
command.ExecuteNonQuery();
// not sure what this is or if its needed
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
}
reader.Close(); //closes reader ----- not sure if this is need since im not reading from a database only writing to
reader = null;
//i assume below here just closes the connections to the data base
dbcmd.Dispose(); //disposes of command
dbcmd = null;
dbconn.Close(); //closes connection to database
dbconn = null;
}
您正在对不包含任何命令的command
变量调用ExecuteNonQuery()
。
摆脱线路:
command.ExecuteNonQuery();
以下行是实际执行您填充的SqliteCommand
的内容:
IDataReader reader = dbcmd.ExecuteReader();
您使用的是command
而不是dbcmd
。
您执行的命令基本上没有附加任何参数或命令。