ado.net 连接数据库

用ado.net连接数据库!

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 第一个mdf
{
    class Program
    {
        static void Main(string[] args)
        {

                //通过SqlCommand类实现连接数据库,并通过using实现资源释放

                using (SqlConnection conn = new SqlConnection(@"Data Source=.; Initial Catalog=master;User Id=sa;Password=******;"))
            {
                conn.Open();
                Console.WriteLine("打开数据库连接成功!!!");
                Console.ReadKey();

                //通过SqlCommand类创建向数据库发送请求的对象cmd

                using (SqlCommand cmd = conn.CreateCommand())
                {

                    //插入了一条Name=元芳的数据
                    cmd.CommandText = "Insert into [Table](Name) Values('元芳')";
                    cmd.ExecuteNonQuery();

                    //ExecuteScalar用于执行一行一列的数据

                    cmd.CommandText = "Select count(*) from [Table] where Name='元芳'";
                    cmd.ExecuteScalar();

                    //下面会造成sql注入漏洞攻击

                    //cmd.CommandText = "Select Id from [Table] where Name='“+1'or'1'='1+”'";

                    cmd.CommandText = "Select Id from [Table] where Name='元芳'";

                    //所以可以用参数化方法避免sql注入漏洞攻击

                    cmd.CommandText = "Select Id from [Table] where Name=@Name";
                    cmd.Parameters.Add(new SqlParameter("@Name","元芳"));
                    using(SqlDataReader reader = cmd.ExecuteReader())
                    while (reader.Read())
                    {
                        int id = reader.GetInt32(0);
                        Console.WriteLine(id);
                        Console.ReadKey();


                }
            }
            Console.WriteLine("执行完成!!!");
            Console.ReadKey();
        }
    }
}

 通过ado.net技术实现了在vs2012里操作数据库,执行结果在sqlserver management studio管理工具里操作是一样的。

posted on 2013-02-19 12:57  蔡嘉  阅读(159)  评论(0编辑  收藏  举报

导航