using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;//数据库连接
using System.Data;//connectionstate使用
namespace WindowsFormsApplication2
{
class Dbhelp
{ ///创建数据库连接字符串///
string connStr = "Data Source=.;Initial Catalog=school;Integrated Security=True";
///数据库连接对象///
SqlConnection conn;
/// <summary>
/// 数据库连接对象
/// </summary>
public SqlConnection Conn
{
get
{
if(conn==null)
{
conn = new SqlConnection(connStr);
}
return conn;
}
set { conn = value; }
}
/// <summary>
/// 打开数据库连接
/// </summary>
public void openconnection()
{
if(conn.State == ConnectionState.Closed)
{
conn.Open();
}
else if(conn.State == ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
}
public void closeconnection()
{
if(conn.State==ConnectionState.Open||conn.State==ConnectionState.Broken)
{
conn.Close();
}
}
}
}
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 WindowsFormsApplication2
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.cboid.SelectedIndex = 0;
}
private void button1_Click(object sender, EventArgs e)
{
if (InputCheck())
{
if (login())
{
if (this.cboid.Text == "学生")
{
Frmstu frmstu = new Frmstu();
frmstu.Show();
this.Hide();
MessageBox.Show("登陆成功");
}
else if (this.cboid.Text == "管理员")
{
Admin admin = new Admin();
admin.Show();
this.Hide();
MessageBox.Show("登陆成功");
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{///关闭///
this.Close();
}
private void txtpassword_TextChanged(object sender, EventArgs e)
{
}
private void txtusername_TextChanged(object sender, EventArgs e)
{
}
private void cboid_SelectedIndexChanged(object sender, EventArgs e)
{
}
public bool InputCheck()
{
bool flag = true;
if (string.IsNullOrEmpty(this.txtusername.Text.Trim()))
{
MessageBox.Show("请输入用户名");
this.txtusername.Focus();
flag = false;
}
else if (string.IsNullOrEmpty(this.txtpassword.Text.Trim()))
{
MessageBox.Show("请输入密码");
this.txtpassword.Focus();
flag = false;
}
else if (this.cboid.Text == "请选择")
{
MessageBox.Show("请选择登陆类型");
flag = false;
}
return flag;
}
public bool login()
{
bool result = false;
Dbhelp db = new Dbhelp();
try
{ ///打开数据库///
db.openconnection();
//创建SQL语句
string sql = string.Format("Select count(*) from login where username='{0}' and password={1}",this.txtusername.Text.Trim(),this.txtpassword.Text.Trim());
//命令对象
SqlCommand comm = new SqlCommand(sql,db.Conn);
//执行并返回判断
int num = (int)comm.ExecuteScalar();
if (num > 0)
{
result = true;
}
else MessageBox.Show("用户名或者密码不正确");
}
catch (Exception ex)
{
MessageBox.Show("error"+ex.Message);
}
finally
{
db.closeconnection();
}
return result;
}
}
}
真心求助。。。着急!
|