在此假设你用的数据库为SQL Server数据库,数据库名为“Test”,用户表名为“Users”,表结构为Users(UserName,Password),代码如下:
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 LoginTest
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
//创建Connection对象
SqlConnection con = new SqlConnection(server=.;database=Test;uid=sa;pwd=);
//创建Command对象
SqlCommand cmd = new SqlCommand(string.Format(SELECT COUNT(*) FROM Users WHERE UserName='{0}' AND Password='{1}',
this.txtUserName.Text.Trim(), this.txtPwd.Text.Trim()), con);
try
{
//打开数据库连接
con.Open();
//如果执行cmd,返回值为1,提示用户登录成功,否则提示登录失败
if ((int)cmd.ExecuteScalar() == 1)
{
MessageBox.Show(登录成功!, 提示, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show(登录失败!, 提示, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
//如果捕获到异常,提示用户数据库操作失败
MessageBox.Show(数据库操作失败! + ex.Message, 提示, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
//关闭数据库连接
con.Close();
}
}
}
}
取消
评论