.net中webform和winform串連sql server 2000資料庫的c#操作類

來源:互聯網
上載者: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)調用樣本:略



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.