gpt4 book ai didi

c# - SqliteDataReader 在 C# 中不起作用?

转载 作者:行者123 更新时间:2023-11-29 06:59:48 25 4
gpt4 key购买 nike

我有一些数据存储在 SQLite 数据库中,我想用 C# 在网页上显示这些数据。我搜索了正确的做法,但只找到了 console.writeline,除此之外,SqliteDataReader 函数不起作用。这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db"))
{
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
command.Connection = conn;

SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
string test = ("Name: " + reader["name"] + "\tScore: " + reader["score"]);

command.ExecuteNonQuery();
conn.Close();
}
}

我该怎么办?

提前致谢,

埃利亚斯

最佳答案

您似乎忘记了要执行的实际查询:

  command.CommandText = "...";

像这样:

protected void Page_Load(object sender, EventArgs e)
{
//TODO: do not hardcode connection string, move it to settings
string connectionString =
@"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";

// var for simplicity
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();

using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;

//TODO: put the right SQL to perform here
command.CommandText =
@"select name,
score
from MyTable";

using (var reader = command.ExecuteReader()) {
string test = "";

// do we have any data to read?
//DONE: try not building string but using formatting (or string interpolation)
if (reader.Read())
test = $"Name: {reader["name"]}\tScore: {reader["score"]}";

//TODO: so you've got "test" string; do what you want with it
}
}

//DONE: you don't want command.ExecuteNonQuery(), but command.ExecuteReader()
//DONE: you don't want conn.Close() - "using" will do it for you
}
}

关于c# - SqliteDataReader 在 C# 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43957023/

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