转自:http://www.codeproject.com/Articles/8477/Using-ADO-NET-for-beginners
使用SqlDataAdapter查询
string strCon = @"Data Source=SONY\MYSQLSERVER;" +
"Initial Catalog=Northwind;Integrated Security=SSPI";
string strSql="select * from customers";
SqlConnection con=new SqlConnection(strCon);
con.Open();
SqlDataAdapter dadapter=new SqlDataAdapter();
dadapter.SelectCommand=new SqlCommand(strSql,con);
DataSet dset=new DataSet();
dadapter.Fill(dset);
con.Close();
this.dataGrid1.DataSource=dset;
SqlDataReader
SqlConnection conn = new SqlConnection("Data Source=CFXIXI\SQLEXPRESS;Initial Catalog=CFXIXIDb;Persist Security Info=True;User ID=sa;Password=123456");
SqlCommand cmd = new SqlCommand("Select * from table", conn);
cmd.CommandTimeout = 400;
SqlDataReader dr;
conn.Open();
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Dispose();
cmd = null;
List<Diamond> list = new List<Diamond>();
while (reader.Read())
{
var diamond = new Diamond
{
PricePerCarat = (Convert.ToDecimal(reader["ListPrice"]) / Convert.ToDecimal(reader["Weight"])).ToString("0"),
PricePerCaratAfterDiscount = (Convert.ToDecimal(reader["SalePrice"]) / Convert.ToDecimal(reader["Weight"])).ToString("0"),
Discount = ((Convert.ToDecimal(reader["SalePrice"]) / Convert.ToDecimal(reader["Weight"])) / (Convert.ToDecimal(reader["ListPrice"]) / Convert.ToDecimal(reader["Weight"]))).ToString("0%"),
DiamondPrice = Convert.ToDecimal(reader["SalePrice"])
};
list.Add(diamond);
}
返回sqldataReader