如何从数据库创建变量和访问值

本文关键字:访问 变量 创建 数据库 | 更新日期: 2023-09-27 18:32:16

我有这样的访问数据库和 oledb 连接:

OleDbConnection Connection;
Connection = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" +
               Server.MapPath("~/db.mdb"));
OleDbCommand Command;
Command = new OleDbCommand("SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1", Connection);
Connection.Open();
OleDbDataReader reader = Command.ExecuteReader();

Select 命令只返回一个 int 值,我需要将此值访问为变量。

我试过了:

int test = reader.GetInt32(0);

返回:行/列不存在数据。

但是数据存在并且选择命令有效。

我该怎么做?

如何从数据库创建变量和访问值

OleDbDataReader第一

行之前开始。如果不调用OleDbDataReader.Read方法,则永远不会到达第一行。

OleDbDataReader.Read方法;

OleDbDataReader 的默认位置在第一个之前 记录。因此,必须调用 Read 才能开始访问任何数据

并使用using语句来处置您的OleDbConnectionOleDbCommandOleDbDataReader

using(OleDbConnection Connection = new OleDbConnection(conString))
using(OleDbCommand Command = Connection.CreateCommand())
{
    Command.CommandText = "SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1";
    using(OleDbDataReader reader = Command.ExecuteReader())
    {
        if(reader.Read())
        {
            int test = reader.GetInt32(0);
        }  
    }
}

如果您只想获取一个数据单元格,ExecuteScalar是更好的选择。它返回第一行的第一列作为object

using(OleDbConnection Connection = new OleDbConnection(conString))
using(OleDbCommand Command = Connection.CreateCommand())
{
    Command.CommandText = "SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1";
    Connection.Open();
    int test = (int)Command.ExecuteScalar();
}

你需要一个阅读器。

[编辑]正如评论中指出的那样,如果您只追求一个值,则最好使用ExecuteScalar。而且您可能还想尝试一下读者。GetInt32(0) 以捕获任何可能的错误...

例如,迭代您的结果。

 if (reader.HasRows)
        {
            while (reader.Read())
            {
                int test = reader.GetInt32(0);
// Do something else
            }
        }

如果你只需要一个值,你可以使用ExecuteScalar方法

 command= new OleDbCommand("SELECT FTPTARIHARALIGI FROM Table1 WHERE ID = 1", Connection);
 command.Connection.Open();
 var value=command.ExecuteScalar();
 connection.Close();

现在值变量具有您想要的值