请参阅以下内容:
public static DataTable GetSqlDataTable(string connStr, string strSqlStatement)
{
DataTable dt = new DataTable();
SqlDataAdapter dA = new SqlDataAdapter();
try
{
SqlConnection conn = new SqlConnection(connStr);
dA.SelectCommand = new SqlCommand(strSqlStatement, conn);
dA.Fill(dt);
return dt;
}
catch (Exception exc)
{
throw exc;
}
}
如何使用object
代替通用数据容器来避免这些通用数据表?
答案 0 :(得分:1)
首先,您需要创建对象:
public class MyObj
{
public string Name { get; set; }
public int ID { get; set; }
}
然后在读取sql数据时创建对象:
private static IEnumerable<MyObj> ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
yield return ReadSingleRow((IDataRecord)reader);
}
// Call Close when done reading.
reader.Close();
}
}
private static MyObj ReadSingleRow(IDataRecord record)
{
return new MyObj{ ID = record[0], Name = record[1]};
}