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)调用示例:略