我有以下代码:
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。谢谢你的帮助!
您可以使用数据适配器:
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; } }