DotNet




SQL:
工厂模式创建DbCommand
    /// <summary>
    /// 创建新的连接对象
    /// </summary>
    /// <returns></returns>
    public static DbCommand CreateCommand()
    {
        string dataProviderName = BalloonShopConfiguration.DbProviderName;
        string connectionString = BalloonShopConfiguration.DbConnectionString;
        ///工厂模式下新建名字为dataProviderName的连接
        DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
        DbConnection conn = factory.CreateConnection();
        ///项数据工厂设置连接字符串
        conn.ConnectionString = connectionString;
        ///创建特定于某数据库的command对象
        DbCommand comm = conn.CreateCommand();
        comm.CommandType = CommandType.StoredProcedure;
        return comm;
    }

执行查询:
    /// <summary>
    /// 执行查询语句
    /// </summary>
    /// <param name="command"></param>
    /// <returns></returns>
    public static DataTable ExecuteSelectCommand(DbCommand command)
    {
        ///将返回的Datatable
        DataTable table;
        try
        {
            //执行该命令
            command.Connection.Open();
            DbDataReader dr = command.ExecuteReader();
            table = new DataTable();
            table.Load(dr);
            dr.Close();
        }
        catch (Exception e)
        {
            Utilities.LogError(e);
            throw;
        }
        finally
        {
            command.Connection.Close();
        }
        return table;
    }

返回Datatable是因为可以使用更少的时间