小编典典

如何将SQL语句作为数据表接收

sql

我有以下代码:

public static DataTable GetDataTable(string sConnStr, string sTable)
{
    DataTable dt = new DataTable();

    SqlConnection sqlConn10 = new SqlConnection(sConnStr);
    sqlConn10.Open();
    SqlCommand sqlComm10 = new SqlCommand("SELECT * FROM " + sTable, sqlConn10);
    SqlDataReader myReader10 = sqlComm10.ExecuteReader();

    try
    {
        while (myReader10.Read())
        {
            // Code needed
        }
    }
    catch
    {
        myReader10.Close();
        sqlConn10.Close();
    }

    return dt;
}

问题是,我不知道如何继续。我想要的只是从SQL语句中获取包含数据的DataTable。谢谢你的帮助!


阅读 201

收藏
2021-03-17

共1个答案

小编典典

您可以使用数据适配器:

public static DataTable GetDataTable(string sConnStr, string sTable)
{
    using (SqlConnection sqlConn10 = new SqlConnection(sConnStr))
    using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM EmployeeIDs", sqlConn10))
    {
        sqlConn10.Open();
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        return dt;
    }
}
2021-03-17