前面曾参加讨论讨论取数据库里面单行数据的问题:现在我要取其中一列int类型数据的SUM合值,根据建议用ExecuteScalar()却有点小问题:
为什么说转换错误????public int SelectSingleValue(string tempStrSQL)
{
this.myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand(tempStrSQL,this.myConnection);
myCommand.Connection.Open();
//取得合值
int intNumber =(int)myCommand.ExecuteScalar();//为什么这里说转换错误呢?
//myConnection.Close();
return intNumber; }另外一个问题:
要取表中指定ID的那行数据记录怎么弄好点?
select * from tb where id = 用户ID
为什么说转换错误????public int SelectSingleValue(string tempStrSQL)
{
this.myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand(tempStrSQL,this.myConnection);
myCommand.Connection.Open();
//取得合值
int intNumber =(int)myCommand.ExecuteScalar();//为什么这里说转换错误呢?
//myConnection.Close();
return intNumber; }另外一个问题:
要取表中指定ID的那行数据记录怎么弄好点?
select * from tb where id = 用户ID
this.myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand(tempStrSQL,this.myConnection);
myCommand.Connection.Open();
object sumNumber = myCommand.ExecuteScalar(); if(sumNumber is DBNull)
{
intNumber = 1;
}
else
intNumber = int.Parse((sumNumber).ToString());
//myConnection.Close();
return intNumber;
SqlDataReader reader = cmd.ExecureReader();
{
// 取各个字段的值
}
SqlCommand md = new SqlCommand("SELECT * FROM tb WHERE id = customerID", conn);
SqlDataReader reader = cmd.ExecureReader();
if (reader.read())
{
// 取各个字段的值
}
还有好的方法吗?
public DataTable DtQuery(string strSql)
{
SqlDataAdapter oleAdapter = new SqlDataAdapter(strSql, Connection);
DataTable dt = new DataTable();
oleAdapter.Fill(dt);
return dt;
}// 执行SQL语句,将结果返回到数据行中。
public DataRow DrQuery(string strSql)
{
SqlDataAdapter oleAdapter = new SqlDataAdapter(strSql, Connection);
DataTable dt = new DataTable();
oleAdapter.Fill(dt);
if (dt.Rows.Count == 0) return null;
else return dt.Rows[0];
}