.net中webform和winform串連sql server 2000資料庫的c#操作類
最後更新:2017-02-28
來源:互聯網
上載者:User
server|web|資料|資料庫 一.這個為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方法-->此方法主要面對的是查(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中的<configuration>下面一行加入資料庫連接字串
<appSettings>
<add key="sqlConn" value="data source=(local); initial catalog=02wangluo;user id=sa; password="/>
</appSettings>
(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)調用樣本:略