.net中webform和winform連線sql server 2000資料庫的c#操作類-.NET教程,資料庫應用

hljhrbsjf發表於2006-09-05
一.這個為c#連線winform
注意點:(1)呼叫時必須引用此類的名稱空間
(2)類中引用的名稱空間
using system;
using system.data;
using system.data.sqlclient;
(3)呼叫示例:
dataset ds =new dataset();
string sql="select * from [user]";
ds=dodatabase.getdataset(sql);
datagrid1.datasource=ds.tables[0].defaultview;
//以上四行為用02wangluo資料庫中user表來填充dataset後繫結到datagrid1
//這是呼叫的getdataset方法--&gt此方法主要面對的是查(select)


string sql="insert into test(test_xingming) values ("+txtuserid.text+")";
dodatabase.executesql(sql);
//以上兩行是呼叫dodatabase資料庫操作類中的executesql方法來執行對資料庫的增,刪,改等操作,一般寫到button_click中
(3)具體操作類程式碼:
public class dodatabase
{
public dodatabase()
{
//
// todo: 在此處新增建構函式邏輯
//
}
public static dataset getdataset(string sql)
{
sqlconnection conn=new sqlconnection();
dataset ds=new dataset();
try
{

conn=new sqlconnection("server=localhost;uid=sa;pwd=;database=02wangluo");
sqldataadapter sda=new sqldataadapter(sql,conn);
sda.fill(ds);
return ds;

}
catch(exception ex)
{
throw(ex);
}
finally
{
conn.close();
}
}
public static int executesql(string sql)
{
sqlconnection conn=new sqlconnection();
try
{
conn=new sqlconnection("server=localhost;uid=sa;pwd=;database=02wangluo");
sqlcommand sqlcmd =new sqlcommand(sql,conn);
conn.open();
return sqlcmd.executenonquery();
}
catch(exception ex)
{
throw ex;
}
finally
{
conn.close();
}
}
}

二asp.net中c#操作sql server 2000資料庫的操作類
(1)類中名稱空間:
using system;
using system.data;
using system.data.sqlclient;
using system.collections;
using system.configuration;
(2)在web.config中的下面一行加入資料庫連線字串



(2)操作類程式碼:
public class dodatabase
{
public static sqlconnection sqlconn = new sqlconnection();
public dodatabase()
{

}
public static dataset getdataset(string sql)
{
dataset ds = new dataset();

try
{
sqlconn = new sqlconnection(configurationsettings.appsettings["sqlconn"]);
sqldataadapter sqlapt = new sqldataadapter(sql, sqlconn);
sqlapt.fill(ds);
return ds;
}
catch (exception ex)
{
throw (ex);
}
}

public static int executesql(string sql)
{
try
{
sqlconn = new sqlconnection(configurationsettings.appsettings["sqlconn"]);
sqlcommand sqlcmd =new sqlcommand(sql,sqlconn);
sqlconn.open();
return sqlcmd.executenonquery();
}
catch (exception ex)
{
throw (ex);
}
finally
{
sqlconn.close();
}
}
}
(4)呼叫示例:略[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/631872/viewspace-863223/,如需轉載,請註明出處,否則將追究法律責任。

相關文章