static fields and static method
此文一出,必然让天下人耻笑.但此错误,切实让我感受到弄清概念是多么重要的一回事.代码仅为说明问题而写:
1public class client
2{
3
4 public DataSet getCustomerInfo()
5 {
6 //return (new DbOper()).getDs("SELECT * FROM CUSTOMERS");
7 return null;
8
9 }
10
11 public DataSet getProductInfo()
12 {
13
14 //return (new DbOper()).getDs("SELECT * FROM PRODUCTS");
15 return DbOper.getDs("SELECT * FROM PRODUCTS");
16 }
17}
调用这访问类2{
3
4 public DataSet getCustomerInfo()
5 {
6 //return (new DbOper()).getDs("SELECT * FROM CUSTOMERS");
7 return null;
8
9 }
10
11 public DataSet getProductInfo()
12 {
13
14 //return (new DbOper()).getDs("SELECT * FROM PRODUCTS");
15 return DbOper.getDs("SELECT * FROM PRODUCTS");
16 }
17}
class DbOper
{
private static SqlConnection conn = null;
public DbOper()
{
conn = new SqlConnection("data source=10.0.0.3;uid=sa;pwd=sa;database=NorthWind");
}
public static DataSet getDs(string sql)
{
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
{
private static SqlConnection conn = null;
public DbOper()
{
conn = new SqlConnection("data source=10.0.0.3;uid=sa;pwd=sa;database=NorthWind");
}
public static DataSet getDs(string sql)
{
SqlDataAdapter da = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
这个例子意在说明类的形成过程:
static fields ----->static method-------->constructor method -------->others
由此可见,在我们调用 getProduct 的时候,构造函数还没有执行,所以conn 对象还没有被初始化.
posted on 2006-04-07 16:45 flyingchen 阅读(164) 评论(0) 编辑 收藏 举报