ADO.NET连接数据库的两种方式

//实现了IDisposable接口的类,用using括起来
//插入数据
string connString = "Data Source=(local);Initial Catalog=Linq;Integrated Security=SSPI";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "insert into orders (Amt,Country,City) values(240,'中国','绍兴');";
cmd.ExecuteNonQuery();
Console.WriteLine("插入成功");
Console.ReadKey();
}
} //用SqlDataReader方式读取数据
string connString = "Data Source=(local);Initial Catalog=Linq;Integrated Security=SSPI";//用windows用户登录
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from orders";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string city = reader.GetString(reader.GetOrdinal("city"));
decimal amt = reader.GetDecimal(reader.GetOrdinal("amt"));
Console.WriteLine(string.Format("城市:{0}, 金额:{1}", city, amt));
}
}
Console.ReadKey();
}
} //用DataSet的方式来连接数据库
string connString = "Data Source=(local);Initial Catalog=Linq;Integrated Security=SSPI";//用windows用户登录
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from orders";
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
/*把查询出来的结果填充到dataset中,并指定一个表面:orders
*注意:
* 如果不指定表名,直接用adapter.Fill(dataset)得方式填充,DataTable接收的时候根据索引号
* DataTable table = dataset.Tables[0];
*/
adapter.Fill(dataset,"orders");
DataTable table = dataset.Tables["orders"];
for (int i = ; i < table.Rows.Count; i++)
{
DataRow row = table.Rows[i];
string city = Convert.ToString(row["city"]);
Console.WriteLine(city);
}
Console.ReadKey();
}
}
上一篇:使用java语言,将字符串中连续重复出现的字母变成“出现次数“+字母的格式


下一篇:WM_INITDIALOG与WM_CREATE消息的区别