关于怎么C#控制台窗口中怎么创建连接查询数据库操作

首先需要新建一张表,为了测试随建了一张学生表

新建号一张表之后就可以对数据库进行操作了

列举了常用的增删改查

操作 

 

        static void Main(string[] args)
        {

 string str1="";
            SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=db_user;Persist Security Info=True;User ID=sa;Password=qwerty");
            SqlCommand sqlcom = new SqlCommand();
            sqlcon.Open();
            sqlcom.Connection = sqlcon;
            Console.WriteLine("请按下面指令操作");
            Console.WriteLine("1.查询所有学生信息");
            Console.WriteLine("2.指定查询指定学生的年龄");
            Console.WriteLine("3.更新学生信息");
            Console.WriteLine("4.删除学生信息");
            Console.WriteLine("5.增加学生信息");
            String check=Console.ReadLine();

      if (check == "1")
            {
              
                sqlcom.CommandText = "select * from tb_stu";
                SqlDataReader read = sqlcom.ExecuteReader();
                while (read.Read())
                {
                    string a = read.GetValue(0).ToString();
                    string a1 = read.GetValue(1).ToString();
                    string a2 = read.GetValue(2).ToString();
                    Console.WriteLine("id:" + a + "   name:   " + a1 + "age:" + a2);
                }
            }

 sqlcom = null;
            sqlcon.Close();
            Console.ReadLine();

}

插入的代码

    sqlcom.CommandText = "insert into tb_stu (name,age) values('"+name+"','"+age+"')";

删除的代码

 sqlcom.CommandText = "delete  from tb_stu where name=+'" + name + "'";

where 条件查询 

          sqlcom.CommandText = "update tb_stu set name='"+ str2+"' where name='"+name+"'";

更新操作

 sqlcom.CommandText = "select age from tb_stu where name='"+name+"'";

 

posted @ 2014-10-28 00:16  初入程序猿  阅读(1024)  评论(0编辑  收藏  举报