我不知道为什么我的连接一直关闭而没有任何关闭连接的东西。我已经尝试将它们封装在using
块中,但无济于事。有没有更好的方法将单个选择查询传递到string
?
private void button2_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
string query = "SELECT isActive FROM tblUser WHERE username = ?username AND password = ?password";
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.AddWithValue("?username", username);
cmd.Parameters.AddWithValue("?password", password);
con.connection.Open();
MySqlDataReader mdr = cmd.ExecuteReader();
string isActive="";
string updatequery = "UPDATE tbluser SET DateLastLogin= '" + DateTime.Today.ToString("dd-mm-yy") + "',TimeLastLogin = '" + DateTime.Now.TimeOfDay + "', IsActive = 1 WHERE username = ?username";
if (mdr.HasRows)
{
if(con.connection.State == ConnectionState.Closed)con.connection.Open();
while (mdr.Read())
{
isActive = mdr[0].ToString();
if (isActive.Equals("1"))
{
MessageBox.Show("This user is already logged in!");
}
else
{
MySqlCommand updatecmd = new MySqlCommand(updatequery, con.connection);
con.OpenConnection();
updatecmd.Parameters.AddWithValue("?username", username);
updatecmd.ExecuteNonQuery();
pnlLogin.Hide();
pnlMenu.Show();
MessageBox.Show("Welcome " + username);
}
}
}
else
{
MessageBox.Show("Invalid user credentials.");
}
}
答案 0 :(得分:0)
由于您没有关闭连接(这是错误的),因此您无需验证您的con是否已关闭以打开它,因此您需要将其删除:
if(con.connection.State == ConnectionState.Closed)con.connection.Open();`
此外,您不需要再次打开您的连接,我相信正在关闭您的连接,因为您在con.OpenConnection();
时使用!isActive.Equals("0")
重新打开它。请尝试删除con.OpenConnection();
并进行检查。
如果您在此代码之后的行后面没有任何新查询,则最好.Close()
您的连接。
答案 1 :(得分:0)
我为Update查询创建了第二个连接语句,并删除了打开连接的其他语句。
private void button2_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = txtPassword.Text;
string query = "SELECT isActive FROM tblUser WHERE username = ?username AND password = ?password";
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.AddWithValue("?username", username);
cmd.Parameters.AddWithValue("?password", password);
con.connection.Open();
MySqlDataReader mdr = cmd.ExecuteReader();
string isActive="";
string updatequery = "UPDATE tbluser SET DateLastLogin= '" + DateTime.Today.ToString("dd-mm-yy") + "',TimeLastLogin = '" + DateTime.Now.TimeOfDay + "', IsActive = 1 WHERE username = ?username";
if (mdr.HasRows)
{
while (mdr.Read())
{
isActive = mdr[0].ToString();
if (isActive.Equals("1"))
{
MessageBox.Show("This user is already logged in!");
}
else
{
MySqlCommand updatecmd = new MySqlCommand(updatequery, con.connection2);
con.connection2.Open();
updatecmd.Parameters.AddWithValue("?username", username);
updatecmd.ExecuteNonQuery();
pnlLogin.Hide();
pnlMenu.Show();
MessageBox.Show("Welcome " + username);
}
}
}
else
{
MessageBox.Show("Invalid user credentials.");
}
con.CloseConnection();
}