0

我正在开发一个从数据库(MS Access)读取用户数据并将信息设置为变量的应用程序。sql 命令需要一个参数来检查数据库中的用户名,但是 OleDbDataReader 显示为空 (userData.HasRows)。

public void UpdatePage(string Username)
    { 
        OleDbDataReader userData;
        string sqlCmd = "SELECT * FROM [Profile Data] WHERE Username = ?";

        TabPage profile = new TabPage();

        using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = LogIn Profiles.accdb;"))
        {
            OleDbCommand cmd = new OleDbCommand(sqlCmd, conn);

            cmd.Parameters.AddWithValue("@Username", Username);

            try
            {
                conn.Open();
                userData = cmd.ExecuteReader();

                if(userData.HasRows)
                {
                    //Used for debugging
                }

                while (userData.Read()) //is not entering into the loop
                {
                    userID = userData[0].ToString();
                    username = userData[1].ToString();
                    password = userData[2].ToString();
                    country = userData[3].ToString();
                    occupation = userData[4].ToString();
                    gender = userData[5].ToString();
                }
                userData.Close();
            }
            catch
            {
                MessageBox.Show("Error 3: Error to connect to database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        } 

当我删除参数并将 sqlCmd 设置为在数据库中设置名称 ("...WHERE Username = 'Mitchell'";) 时,将进入 while 循环并分配变量。惊人的。所以参数发生了一些事情。

此外,我已经确认在调用此方法之前用户数据已在数据库中,因此应该可以找到它。

4

2 回答 2

0

So after hours of playing around with things I found the solution, however I am not totally sure why it works. I had to change the Data Source of the OleDbConnection to the direct file path, rather than the relative path.

Before this method is another that inserts data to the database, and only after the program was closed could it be accessed with this UpdatePage method. Not entirely sure why, however I did have to use the full address in the other method also.

于 2015-02-04T10:22:57.350 回答
0

据我记得,访问不支持命名参数,并且使用“@parm”,其中“parm”与您打算更新的列同名,这可能会暗示...

set ColumnA = ColumnA

与您实际提供的参数相比。这 ”?” 你作为参数的序数占位符是正确的,所以我会尝试从

"@Username" to just "parmUserName"

不要使用“@”符号

于 2015-02-03T14:25:47.237 回答