我有一些数据存储在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();
}
}
我该怎么办?
提前致谢,
利亚
答案 0 :(得分:1)
您似乎忘记执行实际的查询:
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
}
}