SqlHelper类
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StudentSys
{
public class SqlHelper
{
//建立连接
//string connString = "server=127.0.0.1;database=StudentNewDB;Integrated Security=true";//windows身份验证
//string connString = "server=127.0.0.1;database=StudentNewDB;uid=work;pwd=123123";//sqlserver身份验证
private static readonly string connString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
public static object ExecuteScalar(string sql, params SqlParameter[] parameters)
{
SqlConnection conn = new SqlConnection(connString);
//创建Command对象
SqlCommand cmd = new SqlCommand(sql, conn);
//如果是存储过程就要使用这个类别语句 cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddRange(parameters);
//打开连接
conn.Open();
//执行命令
object o = cmd.ExecuteScalar();//只会返回第一行第一列的值
//关闭连接
conn.Close();
return o;
}
}
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connStr" connectionString="server=.;database=StudentNewDB;uid=work;pwd=123123;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
主函数
只是单纯的登录验证
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StudentSys
{
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
/// <summary>
/// 登录系统
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnLogin_Click(object sender, EventArgs e)
{
//获取用户的输入信息
string uName = txtUserName.Text.Trim();
string uPwd = txtUserPwd.Text.Trim();
//判断是否为空
if(string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(uPwd))
{
MessageBox.Show("账号或密码为空!", "登录提示",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserName.Focus();
return;
}
//与数据库通信 检查是否与数据库一致
{
//查询语句 这里是参数化的sql语句,以防止sql注入
string sql = "select count(1) from UserInfo where UserName=@UserName and UserPwd=@UserPwd";
//添加参数
SqlParameter[] parameters =
{
new SqlParameter("@UserName", uName),
new SqlParameter("@UserPwd", uPwd)
};
//调用 因为使用了静态方法,所以调用可以直接调用(而不用先实例化)
object o = SqlHelper.ExecuteScalar(sql, parameters);
//处理结果
if (o == null || o == DBNull.Value ||((int)o) == 0)
{
MessageBox.Show("账号或密码错误!", "登录提示",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("登录成功!", "登录提示",
MessageBoxButtons.OK, MessageBoxIcon.Information);
//转到主页面
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
//非主窗体
//Application.Exit();
}
}
}