第13章 使用ADO.NET访问数据库
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace 打开数据库
{
class Program
{
static void Main(string[] args)
{
#region 连接数据库
//步骤一:配置参数(连接到服务器,连接的数据库名称,用户名,密码)
string str = "Data Source=.;Initial Catalog=Myschool;User ID=sa;pwd=1";
//步骤二:创建Connection对象连接数据库(SqlConnection)
SqlConnection con = new SqlConnection(str);
//步骤三:打开数据库
con.Open();
Console.WriteLine("打开数据库成功!");
//步骤N:将数据库关闭
con.Close();
Console.WriteLine("关闭数据库成功!");
#endregion
#region 数据库异常
try
{
con.Open();
}
catch(SqlException ex){
Console.WriteLine("出现异常"+ex);
}
catch (Exception ex)
{
Console.WriteLine("出现异常!" + ex);
}
finally {
con.Close();
Console.WriteLine("关闭数据库成功!");
}
#endregion
#region 登录
Console.WriteLine("请输入用户名:");
string loginID = Console.ReadLine();
Console.WriteLine("请输入密码:");
string loginPwd = Console.ReadLine();
User user = new User();
user.login(loginID, loginPwd);
#endregion
Console.ReadLine();
}
}
}
ConnectionDB类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace 打开数据库
{
class ConnectionDB
{
static string str = "Data Source=.;Initial Catalog=Myschool;User ID=sa;password=1";
public SqlConnection con = new SqlConnection(str);
public void OpenDB()
{
try
{
con.Open();
}
catch (Exception ex)
{
Console.WriteLine("发生异常!"+ex);
}
}
public void CloseDB()
{
con.Close();
}
}
}
User类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace 打开数据库
{
class User
{
ConnectionDB bd = new ConnectionDB();
public void login(string StudentNo, string loingPwd)
{
string sql = "SELECT COUNT(1) FROM Student WHERE StudentNo='" + StudentNo + "' AND Loginpwd='" + loingPwd + "'";
Console.WriteLine(sql);
bd.OpenDB();
SqlCommand cmd = new SqlCommand(sql, bd.con);
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
Console.WriteLine("登录成功!");
}
else
{
Console.WriteLine("登录失败!");
}
}
}
}