繁体   English   中英

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

[英]How do I create variable and accessing value from database?

我有这样的访问数据库和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);

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

但是数据存在,并且select命令起作用。

我怎样才能做到这一点?

getint之前,您需要一个reader.read。

[EDIT]并且正如注释中所指出的,如果只需要一个值,那么使用ExecuteScalar更好。 而且您可能还想尝试一下Reader.GetInt32(0)来捕获任何可能的错误...

例如迭代您的结果。

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

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方法

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

现在值变量具有所需的值

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM