【发布时间】:2018-07-17 13:09:35
【问题描述】:
我目前正在执行电梯任务,最后一部分是建立一个数据库,记录电梯何时打开以及在哪一层。
团结一致,我得到了这个例外:
"InvalidOperationException: 没有与此关联的连接 命令”
如果您想查看完整项目的副本。
这是我用来尝试创建插入语句的代码
(抱歉,如果 cmets 弄得一团糟,我会这样做,这样我就可以跟踪所有内容)
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;
}
【问题讨论】: