Ado.Net基础

namespace ConsoleApplication2
{
    public class Program
    {
        private static void Main(string[] args)
        {
            string connStr = @"server=.;database=TestDB;uid=sa;pwd=123456;"; //连接用到的字符串
            using (SqlConnection conn = new SqlConnection(connStr)) //创建连接对象
            {
                using (SqlCommand cmd = new SqlCommand()) //创建命令对象
                {
//cmd.CommandText = "insert into Employee (Name) values ('Zhao')";
//cmd.Connection = conn;
//conn.Open();
//int count = cmd.ExecuteNonQuery();

//cmd.CommandText = "select Name,* from Employee";
//cmd.Connection = conn;
//conn.Open();
//object o = cmd.ExecuteScalar();
//Console.WriteLine(o);

                    string uid = "传进来的参数1";
                    string uname = "传进来的参数2";
                    string sql = "select * from Employee where ID=@uid and Name=@uname"; //参数化传值
                    SqlParameter pUid = new SqlParameter("uid", uid);
                    SqlParameter pUname = new SqlParameter("uname", uname); //替换形参
                    cmd.CommandText = sql;
                    cmd.Connection = conn;
                    cmd.Parameters.Add(pUid);
                    cmd.Parameters.Add(pUname);
                        //其实也可以传递一个SqlParameters[],使用cmd.Paramters.AddRange(sqlParameters)不用写那么多代码
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    using (reader)
                    {
                        while (reader.Read()) //指向下一行
                        {
                            for (int i = 0; i < 2; i++) //输出每一行每一列的数据
                            {
                                Console.WriteLine(reader[i].ToString());
                            }
                        }
                    }
//sqlDataAdapter作用是将取到的数据填充到一个DataSet中,DataSet就相当于一个离线数据库,SqlDataAdapter一般是用来填充dataset,dataSet再作为DataGridView的数据源
                    SqlDataAdapter adapter = new SqlDataAdapter("select * from Employee", conn);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);
                    DataTable dt = ds.Tables[0];
                }
            }
            Console.ReadKey();
        }
    }
}

 

posted @ 2016-10-29 15:38  杨老三帅  阅读(112)  评论(0编辑  收藏  举报