C# 如何把数据库内的数据读取出来并赋值给一自定义的变量

我的数据库里有张表A 里面有三个字段a,b,c(是多行的) 现在我想把查询出的字段a的值赋给自己定义的变量x,而且要把与查询出的字段a的值相对应的字段b,c的值赋给自定义另两个变量y,z 代码具体要怎么写呀(最好有注释)

//创建数据库连接
SqlConnection cnn = new SqlConnection("数据库连接字符串");
//构造查询字符串
string str = @"Select top * from A";
//新建SqlCommand对象
SqlCommand cmd = new SqlCommand(str, cnn);
//打开数据库连接
cnn.Open();
//返回dr对象
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
string x = dr["a"].ToString();
string y = dr["b"].ToString();
string z = dr["c"].ToString();
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-12-29
//连接数据库假设为Access数据库
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=domain.mdb;Persist Security Info=True";
OleDbConnection myconn = new OleDbConnection(strCon);
//查询数据
DataSet ds = new DataSet();
try
{
myconn.Open();
OleDbDataAdapter oda = new OleDbDataAdapter("select * from A", myconn);
oda.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (myconn.State == System.Data.ConnectionState.Open)
{
myconn.Close();
}
}

//赋值
DataTable dt = ds.Table[0];
string x = dt.Rows[0]["a"].toString();
string y = dt.Rows[0]["b"].toString();
string y = dt.Rows[0]["c"].toString();
第2个回答  2008-12-29
很简单的咯

DataSet ds = new DataSet();
string x = ds.Tables[0].Rows[0][0].ToString();
string y = ds.Tables[0].Rows[0][1].ToString();
string z = ds.Tables[0].Rows[0][2].ToString();
第3个回答  2008-12-29
你是需要往数组里面赋值吧?
相似回答