ASP.net(C#)利用SQL Server实现注册和登陆功能

时间:2023-03-09 04:53:41
ASP.net(C#)利用SQL Server实现注册和登陆功能

说说我现在吧,楼主现在从事的事IT行业,主攻DotNet技术;当然这次上博客园我也是有备而来,所有再次奉献鄙人拙作,以飨诸位,望诸位不吝赐教。

世界上大多数的工作都是熟练性的工种,编程也不例外,做久了,做多了,自然也就通了!

作为一个程序员,要具有一个程序化的思维,这种思维不是三五两天就能一蹴而就的,它是一个不断累积的过程,就如庖丁解牛一样,做事不仅要掌握规律,还要持着一种谨慎小心的态度,收敛锋芒,并且在懂得利用规律的同时,更要去反复实践,向庖丁“所解数千牛矣”一样,不停地重复,终究会悟出事物的真理所在。所以作为一个初级程序员就更需要通过大量的代码练习来积累自己的代码量。

好了,闲话不多说了。直接进入我们今天的主题————asp.net (C#), 利用SQL Server实现注册和登陆功能!

首先看到题目就要理清思路,第一步做什么,第二步又要做什么,他们之间有何内在联系。

步骤 :

第一步,我们利用SQl语言建立数据库RegistLogin、数据表user、以及创建好约束关系以及插入测试字段(这步简单,就省略过程了)

第二部,我们就打开VS连接到数据库,操作流程见图:

ASP.net(C#)利用SQL Server实现注册和登陆功能

首先我们VS菜单节面找到“视图”单击“服务器资源管理器”如图:

ASP.net(C#)利用SQL Server实现注册和登陆功能

单击“服务器资源管理器”后出现如同界面:

ASP.net(C#)利用SQL Server实现注册和登陆功能

接着出现:

ASP.net(C#)利用SQL Server实现注册和登陆功能

到这一步我们就完成了数据库的连接了 效果图:

ASP.net(C#)利用SQL Server实现注册和登陆功能

接下来,我们就要在VS里进行注册操作了,注册操作无非就是往数据库里插入数据,所以我们创建一个窗应用程序体,添加相应的控件

ASP.net(C#)利用SQL Server实现注册和登陆功能

插入数据代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; namespace 数据库验证
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btnZhuCe_Click(object sender, EventArgs e)
{
string Sql = "Data Source=.;Initial Catalog=RegistLogin;User ID=sa;Password=123";
using (SqlConnection scon = new SqlConnection(Sql))
{
string str = "insert into [User](userName,userPwd ,userEmail ,userPhone ) values('" + txtUserName.Text.Trim() + "','" + txtPwd.Text.Trim() + "','" + txtPhone.Text.Trim() + "','" + txtEmail.Text.Trim() + "')"; scon.Open();
SqlCommand command = new SqlCommand();
command.Connection = scon;
command.CommandText = str;
int obj=command .ExecuteNonQuery(); MessageBox.Show("注册成功"); Form2 f = new Form2();
f.Show(); } }
}
}

再在同一个解决方案里创建登陆窗体:

ASP.net(C#)利用SQL Server实现注册和登陆功能

登陆操作 无非就是检索数据库里的数据是否存在,代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient; namespace 数据库验证
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void btnLogin_Click(object sender, EventArgs e)
{ SqlCommand sqlcmd = new SqlCommand();
string str="select*from user where userName='" + txtAdmin .Text .Trim () + "' and userPwd='" + txtPwd .Text .Trim () + "'";
sqlcmd.CommandText = str; //执行数据
SqlDataReader sqlRead = sqlcmd.ExecuteReader();//读取数据
if (sqlRead.Read())
{
MessageBox.Show("登陆成功!");
}
else
{
MessageBox.Show("用户名或密码错误!");
} } }
}

以上就是所有的流程,如有纰漏,还望大家多多指教!

谢谢!