欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

EF使用SQL语句返回DataTable

程序员文章站 2024-02-20 15:04:04
...

public static DataTable SqlQueryForDataTatable( Database db, string sql)
{

        SqlConnection conn = new System.Data.SqlClient.SqlConnection();
        //conn.ConnectionString = db.Connection.ConnectionString;
        //if (conn.State != ConnectionState.Open)
        //{
        //    conn.Open();
        //}

        conn = (SqlConnection)db.Connection;
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = sql;

        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        adapter.Fill(table);

        conn.Close();//连接需要关闭
        conn.Dispose();
        return table;
    }
相关标签: EF