gpt4 book ai didi

c# - 尝试在 c# 中统一插入 SQLite 数据库

转载 作者:行者123 更新时间:2023-11-30 23:32:32 25 4
gpt4 key购买 nike

我目前正在做电梯作业,最后一部分是建立一个数据库,记录电梯何时打开以及在哪一层。

统一我得到这个异常:

"InvalidOperationException: No connection associated with this command"

如果您想查看完整项目的副本。

https://onedrive.live.com/redir?resid=3F68EB193D2E3399!432&authkey=!AOGf1Et4si0a_k4&ithint=file%2czip

这是我用来尝试创建插入语句的代码

(很抱歉,如果评论弄得一团糟,我会这样做,这样我就可以跟踪所有内容)

 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();

关于c# - 尝试在 c# 中统一插入 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com