C#编写与数据库交互的登陆系统
最近在做WebGis的项目,我负责后端对数据库的操作,比较笨拙,以登陆系统为例写了一些代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace Logdemo
{
class Program
{
static void Main(string[] args)
{
string ConStr = "Data Source=********;Initial Catalog=*****;Integrated Security=True";
try
{
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
if(conn.State==System.Data.ConnectionState.Open)
{
Console.WriteLine("OK");
Console.WriteLine("请输入用户名");
string UserName = Console.ReadLine();
Console.WriteLine("请输入密码");
string pwd = Console.ReadLine();
int n = pwd.Length;
string sql = "select * from 登陆测试 where 用户名='" + UserName + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//cmd.CommandText = "select * from 登陆测试 where 用户名=‘" + UserName + "’";
using (SqlDataReader reader = cmd.ExecuteReader())
{
//Console.WriteLine("1");
cmd.Connection = conn;
if (reader.Read())
{
string rpwd = reader.GetString(reader.GetOrdinal("密码"));
rpwd = rpwd.Substring(0, rpwd.Length - 10+n);
int result = string.Compare(rpwd, pwd);
if (result==0)
Console.WriteLine("登陆成功!");
else Console.WriteLine("登陆失败");
}
else Console.WriteLine("用户名不存在!");
}
}
}
}
catch(Exception e)
{
//Console.WriteLine("Sorry");
}
finally
{
}
Console.Read();
}
}
}
知识点有:
1、数据库的连接
2、数据库的存储格式
3、对不同类型变量的处理和比较