使用ADO.NET 访问数据库

一.ADO.NET :用于连接数据库的技术

1.ADO.NET分为两大组件

DataSet:数据集

.NET FRAMWORK :用于连接到数据库,发送命令,检索结果

2.ADO.NET四大核心对象
Connection
Command
DataAdapter
DataReader

二.使用ADO.NET访问数据库

1.首先导入命名空间System.Data.SqlClient

2.创建连接字符串

String constr="Data Source=.;Initial Catalog=SchoolDB;User=sa;Password=.";


如果没有密码password参数可以省略

3.创建SqlConnection连接对象

SqlConnection con=new SqlConnection(constr);

4.打开数据库连接

con.Open();

在使用数据库之前要保证数据库连接是打开的

con.Close();

使用完数据库之后要关闭连接,释放资源

三.捕获异常

 1 try{
 2      //将可能会发生异常的代码放入到try中
 3 
 4   }catch(异常类型)
 5        //如果try块发生异常,并且异常类型和catch块所捕获的异常类型相匹配,那么会执行catch
 6   {
 7 
 8   }finally{
 9        //无论任何情况都会走到finally块
10   }

捕获异常可以将异常捕获到,而不会导致程序的停止

四.向数据库发送命令

1.创建SQL语句

String sql="select count(*) from Student Where StudentName='"+username+"' and Password='"+Password+"'";

2.使用Command对象发送SQL命令

SqlCommand com=new SqlCommand(sql,con);

3.接收命令执行结果

int count=(int)com.ExecuteScalar();
ExecuteNonQuery()          执行不返回行的语句,如UPDATE等
ExecuteReader()            返回DataReader对象
ExecuteScalar()            返回单个值,如执行带COUNT(*)的SQL语句

4.登录案例

 1 public bool ValidateUser() {
 2                 bool falg=true;
 3                 String constr = "Data Source=.;Initial Catalog=SchoolDB;User=sa;Password=.";
 4                 SqlConnection con = new SqlConnection(constr);
 5                 try
 6                 {
 7                     //打开连接
 8                     con.Open();
 9                     Console.WriteLine("请输入用户名:");
10                     string username=Console.ReadLine();
11                     Console.WriteLine("请输入密码:");
12                     string password = Console.ReadLine();
13                     //1.编写SQL
14                     string sql = "select count(*) from Student where StudentName='"+username+"' and LoginPwd='"+password+"'";
15                     //2.创建Command对象
16                     SqlCommand com = new SqlCommand(sql,con);
17                     int count=(int)com.ExecuteScalar();
18                     if (count > 0)
19                     {
20                     }
21                     else {
22                         falg = false;
23                     }
24                 }
25                 catch (Exception e)
26                 {
27                     Console.WriteLine(e);
28        
29                 }
30                 finally {
31                     con.Close();
32                 }
33                 return falg;
34             }
原文地址:https://www.cnblogs.com/wishsaber/p/9382380.html