我不知道我的错误在哪里..我已经把connection.close()放到了各处。我正在使用microsoft visual studio 2013 C#中的访问数据库。它在没有数据库的情况下运行良好,但是当我尝试向其中添加数据库时,问题就开始发生了。
private void btnLogin_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * from Login where [Username]='" + txtUser.Text + "' and [Password]='" + txtPass.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
connection.Open();
Form main = new AdminMain();
main.Show();
this.Hide();
try
{
connection.Open();
command.Connection = connection;
command.CommandText = "INSERT into LogHisto ([Username],[LogDate],[LogTime]) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
connection.Close();
}
else
{
MessageBox.Show("Username/Password is incorrect");
try
{
connection.Open();
command.Connection = connection;
command.CommandText = "INSERT into LogHisto (Username,LogDate,LogTime) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
connection.Close();
}
答案 0 :(得分:3)
if (count == 1)
{
connection.Open(); // <-------------FIRST TIME
Form main = new AdminMain();
main.Show();
this.Hide();
try
{
connection.Open();// <-------------SECOND TIME
command.Connection = connection;
command.CommandText = "INSERT into LogHisto ([Username],[LogDate],[LogTime]) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
connection.Close();
}
在此代码块中,您打开两次相同的连接,因为您有此异常。只需删除connection.Open()
之一;您还需要删除其中一个connection.Close();
。
此外,您应该在查询中使用参数!这将阻止sql注入。我建议你为DataAccess
制作不同的课程。这样可以防止这样的错误。