关于怎么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+"‘";

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。