1

我使用访问2010和Visual Studio 2012创建我的C#应用​​程序中的数据连接。虽然我搜索有关网络上的代码和我有一样的东西:数据连接建立在C#中访问2012

private void button1_Click(object sender, EventArgs e) 
    { 

     string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; 
    Data Source= " + Application.StartupPath + @"\a.accdb;Persist Security Info=False"; 

    string queryString = @"SELECT userid, password FROM access WHERE userid =" + textBox1.Text + ""; 

    int found = 0; //0 means not found 1 means found 

    using (OleDbConnection connection = new OleDbConnection(connectionString)) 
    { 
     OleDbCommand command = new OleDbCommand(queryString, connection); 
     //we open the database 
     connection.Open(); 
     //we execute the previous query 
     OleDbDataReader reader = command.ExecuteReader(); 

     //this loop will stop until all the rows found have been read 
     while (reader.Read()) 
     { 
      found = 1; 
      Form5 o = new Form5(); 
      o.Show(); 
      this.Hide(); 

     } 
     if (found == 0) 


      MessageBox.Show("Please enter a valid username and password"); 


     reader.Close(); 
    } 

}

但现在我得到一个错误使用相同的代码:

没有为一个或多个必需参数

给定值

我不知道这件事。请给我一个解决这个错误的方法,或者建议我使用数据库连接来完成登录页面的其他完整方法。

回答

2

PASSWORD是访问SQL一个reserved word,所以你需要把它们放在方括号中,类似这样的

string queryString = @"SELECT userid, [password] FROM ... 

编辑回复:发表评论

有你查询另一个问题,从茎事实上,userid是(可能是)文本字段。尝试使用参数化查询,而不是:

string queryString = @"SELECT userid, [password] FROM access WHERE userid = ?"; 

int found = 0; //0 means not found 1 means found 

using (OleDbConnection connection = new OleDbConnection(connectionString)) 
{ 
    OleDbCommand command = new OleDbCommand(queryString, connection); 
    command.Parameters.AddWithValue("?", textBox1.Text); 
    //we open the database 
    connection.Open(); 
    //we execute the previous query 
    OleDbDataReader reader = command.ExecuteReader(); 
+0

我已更改密码,建议您好,但问题仍然存在。 – user3275519

+0

@ user3275​​519我已更新我的答案。 –

+0

非常感谢您爵士!有效。非常感谢!! – user3275519