qtsqlbase 参数化访问数据库 SqlCommand cmd=cnn.CreateCommand()
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.Configuration;
using System.Data.SqlClient;
namespace 复习登录
{
public partial class login : Form
{
public login()
{
InitializeComponent();
}
string str = ConfigurationManager.ConnectionStrings["sqlserver2008"].ConnectionString;
DateTime dt1;
private void btn_login_Click(object sender, EventArgs e)
{
using(SqlConnection cnn=new SqlConnection(str))
{
using (SqlCommand cmd=cnn.CreateCommand())
{
cmd.CommandText = "select * from T_User where username=@username";
cmd.Parameters.AddWithValue("@username", txt_username.Text);
cnn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
int Error = Convert.ToInt32(reader["Error"].ToString());
if (Error >= 3)
{
string sqltime = reader["Errortime"].ToString();
dt1 = DateTime.Parse(sqltime);
DateTime dt2 = DateTime.Now;
TimeSpan ts = dt2 - dt1;
if (ts.TotalMinutes < 5)
{
MessageBox.Show("对不起,你已经输入3次连续错误密码,系统已经将账户冻结,请在五分钟后再试");
return;
}
else
{
clearerror();
}
}
string sqlpassword = reader["Password"].ToString();
if (sqlpassword == txt_password.Text)
{
clearerror();
if (txt_username.Text.ToUpper() == "ADMIN")
{
this.Hide();
main m = new main();
m.Show();
}
else
{
MessageBox.Show("登录成功");
}
}
else
{
MessageBox.Show("密码错误");
adderror();
}
}
else
{
MessageBox.Show("用户名不存在");
}
}
}
}
}
private void adderror()
{
dt1 = DateTime.Now;
using (SqlConnection cnn=new SqlConnection(str))
{
using (SqlCommand cmd=cnn.CreateCommand())
{
cnn.Open();
cmd.CommandText = "update T_User set Error=Error+1,Errortime=@Errortime where username=@username";
cmd.Parameters.AddWithValue("@Errortime", dt1);
cmd.Parameters.AddWithValue("@username", txt_username.Text);
cmd.ExecuteNonQuery();
}
}
}
private void clearerror()
{
using (SqlConnection cnn=new SqlConnection(str))
{
using (SqlCommand cmd=cnn.CreateCommand())
{
cnn.Open();
cmd.CommandText = "update T_User set Error=0 where username=@username";
cmd.Parameters.Add(new SqlParameter("username", txt_username.Text));
cmd.ExecuteNonQuery();
}
}
}
}
}