//实现了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(); } }
时间: 2024-11-02 19:21:17