DO.NET操作数据库
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Data.SqlClient;
7
8 namespace 操作数据库
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 //1.造一个连接字符串
15 string connstring = "server=.;database=mydb;user=sa;pwd=diushiDEwutong0";
16
17 //server指服务器 一般是IP地址,本机使用点
18 //database指数据库名称:要访问的数据库名称
19 //user数据库的用户名:一般是sa
20 //pwd数据库的密码:自己设置的
21 //默认端口号3306
22
23 //2.造一个连接对象(将程序和数据库之间搭建出一个通道)
24 SqlConnection conn = new SqlConnection(connstring);
25
26 //3.在此连接的基础上造一个命令对象,调用CreateCommand命令造对象
27 SqlCommand cmd = conn.CreateCommand();
28
29 //4.给命令对象一个SQL语句
30 cmd.CommandText = "select top 1 * from Nation";
31
32 //******打开链接
33 conn.Open();
34
35 //5.执行SQL语句(命令) 查询和增删改不是一类命令,查询需要返回
36 //返回读取器对象
37 SqlDataReader dr= cmd.ExecuteReader();
38
39 //6.通过读取器来读取数据
40 if (dr.HasRows)
41 {
42 dr.Read();//读取数据方法(读当前指针指向的一条数据,执行完该方法会将指针向下调一个)
43
44 Console.WriteLine(dr[0]);
45 Console.WriteLine(dr[1]);
46 Console.ReadLine();
47 }
48
49 //*****关闭链接
50 conn.Close();
51
52 }
53 }
54 }
作业,给一个条件,查询Info 表的数据
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6 using System.Data.SqlClient;
7
8 namespace 作业
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 string shujuku = "server=.;database=mydb;user=sa;pwd=diushiDEwutong0";
15 SqlConnection conn = new SqlConnection(shujuku);
16 SqlCommand CMD = conn.CreateCommand();
17 Console.WriteLine("请输入要查询的人员姓名");
18 string name = Console.ReadLine();
19 CMD.CommandText = "select * from Info where name='"+name+"'";
20 conn.Open();
21 SqlDataReader dr = CMD.ExecuteReader();
22 if (dr.HasRows)
23 {
24 while (dr.Read())
25 {
26
27 Console.WriteLine(dr[0] + "---" + dr[1] + "---" + dr[2] + "---" + dr[3] + "---" + dr[4]);
28
29
30
31 }
32 Console.ReadLine();
33 }
34 else
35 {
36 Console.WriteLine("查无此人");
37 Console.ReadLine();
38 }
39 conn.Close();
40
41
42 }
43 }
44 }


浙公网安备 33010602011771号