想通过按钮实现对用户的注册,数据库中用户名为主键所以一旦重复自己报错
调试过程中出现“已有打开的与此command相关联的DataReader,必须先将其关闭”
小白求教 还希望能帮着看看我写的这段代码还有其他什么问题吗 谢谢谢谢
private void button1_Click(object sender, EventArgs e)
{
string username, password1, password2;
string conString = @"Data Source=LETEMPS;Initial Catalog=海景影城;Integrated Security=true;Pooling=False";
SqlConnection conn = new SqlConnection(conString);
try
{
string cmd = "INSERT INTO 用户名信息表(用户姓名,用户名,密码,联系方式)VALUES('"+textBox1.Text+ "','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"')";
SqlCommand com = new SqlCommand(cmd, conn);
//创建数据库连接
username = textBox2.Text;
password1 = textBox3.Text;
password2 = textBox5.Text;
if (password1 == password2)
{
try
{
//创建数据库查询命令
SqlCommand scmd = new SqlCommand();
scmd.Connection = conn;
//使用SqlCommand对象的ExecuteReader方法查询所有影院的编号,名称,地点和联系方式操作
scmd.CommandText = @"select 用户名 from 用户名信息表";
//定义查询方法
conn.Open();
SqlDataReader reader = scmd.ExecuteReader(CommandBehavior.CloseConnection);
if (com.ExecuteNonQuery() != 0)//com.ExecuteNonQuery()执行语句,并返回受影响行数
MessageBox.Show("注册成功!");
else
MessageBox.Show("注册不成功!");
conn.Close();//关闭
}
catch (Exception error)
{
//输入异常
MessageBox.Show(error.Message, "输入异常", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();//关闭连接
conn.Dispose();//清除连接
}
}
else
{
//两次输入的密码不相同,给出提示
MessageBox.Show("两次输入的密码不同!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "操作数据库出错", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conn.Close();
}
}