日期:2014-05-18  浏览次数:20888 次

如何调用数据库操作类?
我要调用一个完成双向数据库操作的方法,但总是出错:CS0176: 无法使用实例引用访问成员“DB.getDs(string)”;请改用类型名称对其加以限定! 
请各位老大看看我哪里用的不对,谢谢 

CS文件调用代码如下: 
DB dr = new DB(); 
string sql = "select * from Users where UserName = '" + strName + " '"; 
dr.getDs(sql); 

类文件代码: 
public static DataSet getDs(string sql) 
  { 
  SqlConnection conn = getConn(); 
  conn.Open(); 
  SqlCommand cmd = new SqlCommand(sql, conn); 
  SqlDataAdapter ada = new SqlDataAdapter(cmd); 
  DataSet ds = new DataSet(); 
  ada.Fill(ds); 
  conn.Close(); 
  return ds; 
  }

------解决方案--------------------
static不用实例访问的,你可以直接DB.getDs(sql);
------解决方案--------------------
要么直接调用DB.getDs方法,要么将static去掉。
方法1:
string sql = "select * from Users where UserName = '" + strName + " '";
DataSet ds = DB.getDs(sql);

方法2:
DB dr = new DB();
string sql = "select * from Users where UserName = '" + strName + " '";
DataSet ds = dr.getDs(sql);

public DataSet getDs(string sql)
{
SqlConnection conn = getConn();
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
conn.Close();
return ds;
}
------解决方案--------------------
你的是return ds; 带返回函数。。用的时候需要定义dataset得到值!如:
DB dr = new DB();
string sql = "select * from Users where UserName = '" + strName + " '";
dataset ds=dr.getDs(sql);



记得把 static 去掉

------解决方案--------------------
3楼的:
要么直接调用DB.getDs方法,要么将static去掉。 
方法1: 
string sql = "select * from Users where UserName = '" + strName + " '";
DataSet ds = DB.getDs(sql);

方法2: 
DB dr = new DB();
string sql = "select * from Users where UserName = '" + strName + " '";
DataSet ds = dr.getDs(sql);

public DataSet getDs(string sql)
{
SqlConnection conn = getConn();
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ada.Fill(ds);
//SqlConnection对象不用关!
conn.Close();
return ds;
}