本帖最后由 盘晟 于 2013-5-14 12:33 编辑
代码如下: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 Form1_Load(object sender, EventArgs e)
{
}
private void IncErrorTimes()
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\360安全浏览器下载\第一个mdf\练习案例\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand updatecmd = conn.CreateCommand())
{
updatecmd.CommandText = "Update T_Users Set ErrorTimes=ErrorTimes+1 where UserName=@UserName";
updatecmd.Parameters.Add(new SqlParameter("UserName", txtUserName.Text));
updatecmd.ExecuteNonQuery();
}
}
}
private void RsetErrorTimes()
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\360安全浏览器下载\第一个mdf\练习案例\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using (SqlCommand updatecmd = conn.CreateCommand())
{
updatecmd.CommandText = "Update T_Users Set ErrorTimes=0 where UserName=@UserName";
updatecmd.Parameters.Add(new SqlParameter("UserName", txtUserName.Text));
updatecmd.ExecuteNonQuery();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\360安全浏览器下载\第一个mdf\练习案例\Database2.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
using(SqlCommand cmd=conn.CreateCommand())
{
cmd.CommandText = "select * from T_Users where UserName=@UserName";
cmd.Parameters.Add(new SqlParameter("UserName",txtUserName.Text));
cmd.ExecuteReader();
using(SqlDataReader reader=cmd.ExecuteReader())
{
if (reader.Read())
{
int Errortimes=reader.GetInt32(reader.GetOrdinal("ErrorTimes"));
if (Errortimes > 3)
{
MessageBox.Show("登录次数过多,禁止登录!");
return;
}
string dbPassword = reader.GetString(reader.GetOrdinal("Password"));
if (dbPassword == txtPassword.Text)
{
MessageBox.Show("登录成功");
RsetErrorTimes();
}
else
{
IncErrorTimes();
//在同一个连接中如果SqlDataReader没有关闭,是不能执行Update之类的语句的
//using(SqlCommand updatecmd=conn.CreateCommand())
//{
// updatecmd.CommandText="Update T_Users Set ErrorTimes=ErrorTimes+1 where UserName=@UserName";
// updatecmd.Parameters.Add(new SqlParameter("UserName",txtUserName.Text));
// updatecmd.ExecuteNonQuery();
MessageBox.Show("登录失败");
}
}
else
{
MessageBox.Show("登录失败");
}
}
}
}
}
}
}
运行的时候出现如下问题:
怎么办啊?真的找不到哪里错了!
|
|