码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2016-04-20 11:20:09      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

//实现了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();
    }
}

 

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

标签:

原文地址:http://www.cnblogs.com/yangyong-yy/p/5411703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!