public static string conString = @"Server=localhost;Integrated Security=True; Database=northwind";
1. 执行Sql语句, 返回受影响的行数
Code
string conString = @"Server=localhost;Integrated Security=True; Database=northwind";
//执行SQL语句, 返回受影响的行数
public int ExecuteSql(string strSql)
{
SqlConnection thisConnection = new SqlConnection(conString);
SqlCommand thisCommand = new SqlCommand(strSql, thisConnection);
thisConnection.Open();
int rows = thisCommand.ExecuteNonQuery();
thisConnection.Close();
return rows;
} 调用方法:
string strSql=@"select * from Customers";
int rows = ExecuteSql(strSql);
不知道为什么, 测试了一下, 返回的rows竟然是-1. 暂时没有找到原因.
2. 执行查询语句, 返回DataSet
Code
//执行SQL语句,返回DataSet
public static DataSet Query(string strSql)
{
SqlConnection thisConnection = new SqlConnection(conString);
DataSet thisDataSet = new DataSet();
thisConnection.Open();
SqlDataAdapter thisAdapter = new SqlDataAdapter(strSql, conString);
thisAdapter.Fill(thisDataSet, "ds");
thisConnection.Close();
return thisDataSet;
} 调用方法:
string strSql = @"select * from Customers";
DataSet ds = Utility.Query(strSql);
3. 执行一条计算查询结果语句, 返回查询结果(object)
Code
//执行一条计算查询结果语句,返回查询结果(object)
public static object GetSingle(string strSql)
{
SqlConnection thisConnection = new SqlConnection(conString);
SqlCommand thisCommand = new SqlCommand(strSql, thisConnection);
thisConnection.Open();
object obj = thisCommand.ExecuteScalar();
if((Object.Equals(obj,null))||(Object.Equals(obj,System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
} 调用方法:
string strSql = @"select * from Customers";
string num = Utility.GetSingle(strSql).ToString();
5. 带参数, 执行SQL语句, 返回影响的记录数
..............