再问个小问题???
我在程序中定义一个string
我定义的string 怎样来得到数据库中的数据哦...
如:string str;
table A
id name
1 a
2 b
sql: select name from A where id = 1
我怎样来得到str=a???
------解决方案--------------------string strSql = "select name from A where id = 1 ";
SqlDataAdapter myCommand = new SqlDataAdapter(strSql, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "t_dict ");
DataView dv = new DataView();
str=ds.Tables[ "A "].Columns[0].Caption;
------解决方案--------------------- -!
为什么那么复杂
string strSql = "select name from A where id = 1 ";
SqlCommand comm = new SqlCommand(strSql, myConnection);
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
str = dr.GetString(0);
}
------解决方案--------------------string strSql = "select name from A where id = 1 ";
SqlCommand comm = new SqlCommand(strSql, myConnection);
SqlDataReader dr = comm.ExecuteReader();
while (dr.Read())
{
str = dr.GetString(0);
}
是個好方法,用SqlDataReader比較快,
可是這段代碼存在著隱憂,
問題出在dr.GetString(0);這句,當數據庫中的name字段空時
vs會報DBNull錯的,
應該用dr[0].ToString();就不會有錯了