数据库操作类的封装


        public static string conString = @"Server=localhost;Integrated Security=True; Database=northwind";

1. 执行Sql语句, 返回受影响的行数
ContractedBlock.gifExpandedBlockStart.gifCode
        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
ContractedBlock.gifExpandedBlockStart.gifCode
        //执行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)
ContractedBlock.gifExpandedBlockStart.gifCode
        //执行一条计算查询结果语句,返回查询结果(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语句, 返回影响的记录数
..............

转载于:https://www.cnblogs.com/niuniu1985/archive/2009/09/10/1564246.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值