且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从sql表中检索值并将其存储在变量中.

更新时间:2022-12-12 10:06:36

对DataReader以及如何遍历结果行进行更多研究.

调用ExecuteReader()的目的是返回查询产生的一组行.因此,您要做的就是检查您的DataReader是否具有"HasRows",如果是,则将遍历这些行以从中提取字段(或列")数据. >
Do some more research on the DataReader and how to iterate through your resulting rows.

The call to ExecuteReader() is geared toward returning a set of rows resulting from your query. So, what you''ll want to do is check to see if your DataReader "HasRows", and if it does, you will loop through those rows to extract field (or ''column'') data from them.

OleDbConnection dbConnection = new OleDbConnection();
OleDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandText = "select * from tbl where user=''example''";
OleDbDataReader dbReader = dbCommand.ExecuteReader();
int cashValue = 0;
if (dbReader.HasRows)
{
    while (dbReader.Read())
    {
        cashValue = Convert.ToInt32(dbReader["cash"]);
    }
}


if (dataread.HasRows)
{
    while (dataread.Read())
    {
        cashstring = (dataread.GetSqlValue(0).ToString());
    }
}
dataread.Close();
cash = int.Parse(cashstring);



如fcronin所说进行了一些研究.这对我来说非常有效.谢谢=]



Did some research as fcronin said. This worked perfectly for me. Thank you =]


如果您的意图仅仅是从SQL读取单个值.去执行标量而不是执行阅读器.

If your intension is just to read a single value from SQL. Go for execute scalar instead of execute reader.

object objResult = dbCommand.ExecuteScalar();
int result;
if(objResult != null)
{
if(Int.TryParse(objResult,result out))
Console.Write("Result is: "+ result);
else
Console.Write("No data Found");
}