提供者&询问

时间:2013-11-27 15:21:49

标签: c# sql generics datatable provider

我想创建一个可以创建和填充DataTable的C#应用​​程序。

这是我的代码:

public DataTable GetData(string query)
{
    DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");

    using (DbConnection conn = factory.CreateConnection())
    {
        try
        {
            DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder();
            csb["Data Source"] = @"";
            csb["User Id"] = @"";
            csb["Password"] = @"";

            conn.ConnectionString = csb.ConnectionString;
            conn.Open();

            using (DbCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = query;

                using (DataTable dt = new DataTable())
                {
                    DbDataAdapter da = factory.CreateDataAdapter();
                    cmd.CommandType = CommandType.Text;
                    da.SelectCommand = cmd;
                    da.Fill(dt);
                    return dt;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error", ex);
        }
        finally
        {
            if (conn.State != ConnectionState.Closed)
                conn.Close();
        }
    }
}

第二次,我有一个包含各种查询的课程。

public class Query
{
    public string SQL;

    public string query1()
    {
        this.SQL = "select * from table1"
        return this.SQL;
    }

    public string query2(string param)
    {
        this.SQL = "select * from table1 where id = '" + param + "' ";
        return this.SQL;
    }

我希望我可以将query1和/或query2作为我的方法GetData的参数。

public DataTable GetData(query1)
{
    //...
}

但我不知道怎么做! 提前感谢您的帮助!

0 个答案:

没有答案