数据未更新到表格中。

3

我正在尝试实现密码更改功能,但似乎无法正常工作。

 private void button3_Click(object sender, EventArgs e)
    {

        using (OleDbConnection con = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\Users\User\Desktop\esoft\gym\gym\bin\Debug\Clients.accdb"))
        {
            DataTable dt = new DataTable();
            con.Open();
            errorProvider1.Clear();
            if (dt.Rows[0][0].ToString() == "1")
            {
                if (textBox3.Text == textBox4.Text)
                {

                    OleDbDataAdapter da = new OleDbDataAdapter(" COUNT (*) FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
                    OleDbCommand com = new OleDbCommand("UPDATE login SET [password] = '" + textBox3.Text + "' WHERE username = '" + textBox2.Text + "'", con);
                    com.ExecuteNonQuery();



                    MessageBox.Show("password successfully changed", "success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    errorProvider1.SetError(textBox3, "passwords dont match");
                    errorProvider1.SetError(textBox4, "passwords dont match");
                }
            }

            else
            {
                errorProvider1.SetError(textBox1, "wrong username");
                errorProvider1.SetError(textBox2, "wrong pasword");

            }

        }
    }

在第if (dt.Rows[0][0].ToString() == "1")行出现了错误,指出该位置没有找到数据,但是数据表中有5行。

当代码运行时去掉上述行,如//if (dt.Rows[0][0].ToString() == "1")

代码可以运行,但是表中没有数据被更新。

再次更新代码,仍然收到相同的错误:

OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            con.Open();
            errorProvider1.Clear();
            if (dt.Rows[0][0].ToString() == "1")

更大的问题是你试图存储密码。不要这样做!!! - Mitch Wheat
1
con.read() 没有了,我想。 - null1941
2
您刚刚创建了一个新的 DataTable 实例,但没有为其分配任何数据! - Salah Akbari
代码片段中没有查询来填充 DataTable。 - null1941
4个回答

2
尝试按照以下方式填充您的DataTable -
string cmdString = "SELECT * FROM login WHERE username= '" + textBox1.Text + "' AND [password]='" + textBox2.Text + "' ";
OleDbCommand cmd = new OleDbCommand(cmdString,con);
con.Open();
var dr = cmd.ExecuteReader();

DataTable dt = new DataTable();
dt.Load(dr);
con.Close()

现在,只要你的查询语句正确,你就可以在表格中获取数据。确保在连接和命令对象上使用 using 块,在超出范围时将它们释放。


那也不行:/ 当我输入错误的用户名时,仍然会出现相同的错误(找不到数据),而不是显示错误提供程序。当我尝试更改现有用户名的密码时,它显示为已保存,但实际上没有更新任何数据。 - iboss
好的。我已经试着调试代码很久了,无论我怎么做都会得到同样的错误,即没有找到数据等。但我确保我的数据表中有5行数据,并且所有其他使用相同连接字符串的表单都能正常工作,除了另一个也是更新表单的表单。那么这里出了什么问题... - iboss

1
你只是在声明数据表,而没有分配任何数据。
DataTable dt = new DataTable();

这就是为什么当您尝试获取dt.Rows [0] [0] .ToString()时会出现错误的原因。


@iboss - 请在问题中更新您所做的更改以及出现的错误细节。 - Yogi

0

你可以试一试这个:

OleDbDataAdapter custDA = new OleDbDataAdapter();
     DataSet custDS = new DataSet();
     DataTable custTable = new DataTable("Customers");
     custTable.Columns.Add("CustomerID", typeof(String));
     custTable.Columns.Add("CompanyName", typeof(String));
     custDS.Tables.Add(custTable);
     //Use ADO objects from ADO library (msado15.dll) imported
     //  as.NET library ADODB.dll using TlbImp.exe
     ADODB.Connection adoConn = new ADODB.Connection();
     ADODB.Recordset adoRS = new ADODB.Recordset();
     adoConn.Open("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;", "", "", -1);
     adoRS.Open("SELECT CustomerID, CompanyName FROM Customers", adoConn, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
     custDA.Fill(custTable, adoRS);
     adoRS.Close();
     adoConn.Close();

你可以点击reference进行跟进。

谢谢您的建议,但这个项目是我的课程作业的一部分,我们不应该使用除了OleDb之外的任何东西。 - iboss

0
正如另一个人所指出的,你从未为数据表分配任何值,这就是它出错的原因。通过字符串连接来构建查询会让你容易受到 SQL 注入的攻击,应该将其参数化。最后,在你的查询中,我会根据给定的用户ID查询所有记录,但是只根据用户ID获取用户名和密码的值,而不是密码。这样,如果返回超过1行,就表示存在重复的用户账户,需要特别注意。如果返回没有记录,则表示不存在该用户。如果返回一行记录,那么你可以将其与输入的密码进行比较,如果匹配,就找到了正确的用户ID可以使用。
从你的开始。
using( OleDbConnection con = ...) 
{
   // create command first.. Parameterize it.  In this case "@" is parameter indicator
   // for Access.  parmUserName is the parameter name to be applied.  I explicitly added
   // "parm" in front to ensure differentiation between the parameter and actual column.
   var cmd = new OleDbCommand( 
               @"select password from login where username = @parmUserName", con);

   // Now, add the parameter of proper data type.  The name of the parameter and it's value
   cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);

   // create your data adapter now based on the command above
   var da = new OleDbDataAdapter(cmd);

   // NOW, create your data table object and have data adapter query and fill with rows.
   var dt = new DataTable();
   da.Fill(dt);

   // NOW, check results.
   if (dt.Rows.Count == 0)
      MessageBox.Show("No such user account");
   else if( dt.Rows.Count > 1)
      MessageBox.Show("Duplicate user account");
   else
   {
      // valid single record. Do the passwords match?
      if (textBox3.Text.Equals(dt.Rows[0]["password"].ToString()))
      {
         MessageBox.Show("Valid login, allow to continue");

         // Now, since it appears you are trying to UPDATE the password for the user,
         // build new UPDATE command and parameterize it in a similar fashion
         var cmdUpd = new OleDbCommand(
                        @"update login set password = @parmNewPwd where username = @parmUserName", con);
         // Now, add the parameter of proper data type.  The name of the parameter and it's value
         cmd.Parameters.AddWithValue("parmNewPwd", textBox3.Text);
         cmd.Parameters.AddWithValue("parmUserName", textBox1.Text);
         if (cmd.ExecuteNonQuery() == 1)
            MessageBox.Show("Password updated");
         else
            MessageBox.Show("Failed updating password");
      }
      else
         MessageBox.Show("Invalid password");
   }
}

最后提醒。在构建 SQL 命令之前,您还应该考虑清理数据。永远不要将字符串连接起来,因为用户可能会手动输入数据进行 SQL 注入攻击,请对它们进行参数化处理。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接