【问题标题】:SqliteDataReader doesn't work in C#?SqliteDataReader 在 C# 中不起作用?
【发布时间】:2017-05-13 19:09:11
【问题描述】:

我有一些数据存储在 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();
        }
    }

我该怎么办?

提前致谢,

埃利亚斯

【问题讨论】:

  • 您的查询是什么? IE。你必须把command.CommandText = "...";

标签: c# html mysql database sqlite


【解决方案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 
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2015-09-08
    • 2014-04-29
    • 2018-03-04
    相关资源
    最近更新 更多