这里只是用最短的代码陈述了如何完成登录注册的功能,所以不考虑代码的饱满和稳定性,比如没有 close() 函数。
登录源码:
这里要注意sql语句中的表名要加上 [ ] 否则会报错
using System.Data.SqlClient;
// 初始化数据库连接
SqlConnection conn = new SqlConnection("Data Source=你的服务器ip地址;Initial Catalog=你要连接的数据库名;Persist Security Info=True;User ID=你的数据库用户名;Password=你的数据库密码");
conn.Open();
// 编辑 SQL 语句
SqlCommand cmd = new SqlCommand("select phoneNum,passWd from [user] where phoneNum='" + textBox1.Text + "'and passWd='" + textBox2.Text + "'", conn);
// 遍历 user 表
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
int n = da.Fill(ds);
if (n!=0)
{
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show("用户名或密码错误");
}
注册源码:
using System.Data.SqlClient;
// 初始化数据库
SqlConnection conn = new SqlConnection("Data Source=你的服务器ip地址;Initial Catalog=你要连接的数据库名;Persist Security Info=True;User ID=你的数据库用户名;Password=你的数据库密码");
conn.Open();
// 编辑SQL语句
SqlCommand cmd = new SqlCommand("select phoneNum from [user] where phoneNum='" + textBox1.Text + "'", conn);
// 遍历 user 表
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
int n = da.Fill(ds);
if (n!=0)
{
MessageBox.Show("用户已存在,注册失败");
}
else
{
// 插入数据
cmd = new SqlCommand("insert into [user](phoneNum,passWd) values('"+textBox1.Text+"','"+textBox2.Text+"')", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("注册成功");
}