static void Main(string[] args)
{
#region 连接数据库
//步骤1:配置参数(连接到的服务器,连接的数据库名称,用户名,密码)
string constr = "Data Sour .;Initial Catalog=MySchool;User ID sa;Pwd=1";
//步骤2:创建Connection对象链接数据库(SqlConnection)
SqlConnection con = new SqlConnection(constr);
con.Open();
Console.WriteLine("打开MySchool数据库成功!");
con .Close();
Console.WriteLine("关闭MySchool数据库链接成功");
#endregion
#region 捕获异常
//步骤1:配置参数(连接到的服务器,连接的数据库名称,用户名,密码)
string constr = "Data Sour .;Initial Catalog=MySchool;User ID sa;Pwd=1";
//步骤2:创建Connection对象链接数据库(SqlConnection)
SqlConnection con = new SqlConnection(constr);
try
{
//将可能会发生运行时异常的代码放入try块中
con.Open();
Console.WriteLine("打开MySchool数据库成功!");
}
catch (SqlException ex)
{
Console.WriteLine("SqlException异常"+ex);
}
catch (Exception ex)
{
Console.WriteLine("Exception异常"+ex);
}
finally
{
con .Close();
Console.WriteLine("关闭MySchool数据库链接成功");
}
#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();
}
}
class ConnectionDB
{
//准备链接字符串
static string str = "Data Source=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();
}
}
class User
{
ConnectionDB db = new ConnectionDB();
//登陆方法
public void Login(string loginID,string loginPwd)
{
//如何登陆
//步骤1:创建一个Command对象
string sql="SELECT COUNT(1) FROM Login WHERE LoginID'" + loginID + "' AND LoginPwd'"+loginPwd+"'";
Console.WriteLine(sql);
//打开数据库链接
db.OpenDB();
SqlCommand cmd =new SqlCommand(sql,db.con);
//步骤2:接收数据库返回值
int count=(int)cmd.ExecuteScalar();
//步骤3:判断返回值
if (count >0)
{
Console.WriteLine("登陆成功!");
}
else
{
Console.WriteLine("登陆失败!");
}
}
}