Server *** 作,一般就是使用
SQLConnection对象,如果要连接ACCESS或Excel
就以用到OLEDBConnection对象。如果是要对SQL
Server数据库增、删、改、查的 *** 作,就还要用到:
–
Command对象,用于执行SQL命令
–
AdapterData对象(数据适配器)
,是连接数据库与数据集的数据桥梁
–
DataSet
对象(数据集),存放数据的内存区域
–
DataReader
对象(数据阅读器)
,用于执行Command命令后高速读取数据
做一个DBHelper类在,数据访问层中直接调用它public class DBHelper
{
private static SqlConnection connection
public static SqlConnection Connection
{
get
{
string connectionString = "server=(local)\\db2005database=MyBookShopuid=sapwd=sasa"
//string connectionString = ConfigurationManager.ConnectionStrings["MyConstr"].ConnectionString
if (connection == null)
{
connection = new SqlConnection(connectionString)
connection.Open()
}
else if (connection.State == System.Data.ConnectionState.Closed)
{
connection.Open()
}
else if (connection.State == System.Data.ConnectionState.Broken)
{
connection.Close()
connection.Open()
}
return connection
}
}
public static int ExecuteCommand(string safeSql)
{
SqlCommand cmd = new SqlCommand(safeSql, Connection)
int result = cmd.ExecuteNonQuery()
return result
}
public static int GetScalar(string safeSql)
{
SqlCommand cmd = new SqlCommand(safeSql, Connection)
int result = Convert.ToInt32(cmd.ExecuteScalar())
return result
}
public static SqlDataReader GetReader(string safeSql)
{
SqlCommand cmd = new SqlCommand(safeSql, Connection)
SqlDataReader reader = cmd.ExecuteReader()
return reader
}
public static DataTable GetDataSet(string safeSql)
{
DataSet ds = new DataSet()
SqlCommand cmd = new SqlCommand(safeSql, Connection)
SqlDataAdapter da = new SqlDataAdapter(cmd)
da.Fill(ds)
return ds.Tables[0]
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)