您的位置:首页 > 数据库

[C#] 连接数据库并进行用户注册

2012-04-06 13:29 162 查看
连接数据库,并进行用户注册.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace 注册
{
class Program
{
static void Main(string[] args)
{
//下面这段文字的作用已经在其它博文中解释!
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(@"\bin\Debug\")
|| dataDir.EndsWith(@"\bin\Release\"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}

//定义变量
string username, password1, password2;
SqlConnection conn=null;
SqlCommand cmd = null;
SqlDataReader reader = null; ;

Console.WriteLine("输入用户名:");//提示输入用户名
username = Console.ReadLine().Trim();
Console.WriteLine("请输入密码:");//提示输入密码
password1 = Console.ReadLine().Trim();
Console.WriteLine("请再输入一次密码:");//提示再输入密码
password2 = Console.ReadLine().Trim();

//判断两次输入的密码是否相同,如果不相同,就给出提示;
if (password1 == password2)
{
try
{
//创建数据库连接
conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DataBase1.mdf;Integrated Security=True;User Instance=True");
conn.Open();//打开数据库

//创建数据库查询命令
cmd = conn.CreateCommand();
cmd.CommandText = "select * from T_Users where UserName='" + username + "'";

//定义查询方法
reader = cmd.ExecuteReader();

//如果(!reader.Read())的返回结果是真,说明reader.Read()假, 说明数据库中没有相同的用户名
if (!reader.Read())
{
reader.Close();//关闭reader

//重新定义数据库查询语言
cmd.CommandText = "Insert into T_Users(UserName,PassWord) Values('" + username + "','" + password1 + "')";
cmd.ExecuteNonQuery();//执行查询语言
Console.WriteLine("注册成功");  //给出提示,注册成功
}
else
{
//如果(!reader.Read())为假,说明reader.Read()为真,数据库中没有相同的用户名
Console.WriteLine("你输入的用户名已存在!");
}
}
catch (Exception error)
{
//输入异常
Console.WriteLine(error.Message);
}
finally
{

reader.Close();//关闭
reader.Dispose();//清除
conn.Close();//关闭连接
conn.Dispose();//清除连接
}
}
else
{
//两次输入的密码不相同,给出提示
Console.WriteLine("两次输入的密码不同!");
}
Console.ReadKey();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐