简体   繁体   English

数据未更新到表

[英]data not being updated to table

I'm trying to implement a password change feature but it doesn't seem to want to work. 我正在尝试实现密码更改功能,但它似乎不想工作。

 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");

            }

        }
    }

there is an error in the line if (dt.Rows[0][0].ToString() == "1") where it states that no data was found at that position, yet there are 5 rows in the data table. if (dt.Rows[0][0].ToString() == "1")行中有一个错误,它表明在该位置没有找到数据,但数据表中有5行。

when the code is run without the above line, as in //if (dt.Rows[0][0].ToString() == "1") 当代码在没有上述行的情况下运行时,如//if (dt.Rows[0][0].ToString() == "1")

the code runs but no data is being updated in the table. 代码运行但表中没有更新数据。

updated code again and still recived the same error: 再次更新代码并仍然收到相同的错误:

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")

Try filling your DataTable as following - 尝试按以下方式填写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()

Now you should get your data in table, provided that your select query is correct. 现在,您应该在表中获取数据,前提是您的选择查询是正确的。 Make sure you use using blocks on connection and command objects to dispose these when they are out of scope. 确保在连接和命令对象上using块来在超出范围时使用using块。

you are just declaring data table,not assigning any data 您只是声明数据表,而不是分配任何数据

DataTable dt = new DataTable();

thats why when you try to get dt.Rows[0][0].ToString() it gives error 这就是为什么当你试图得到dt.Rows[0][0].ToString()它会给出错误

As you can try this: 你可以试试这个:

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();

You can follow this reference 您可以按照此参考

As noted by another, you never assign a value to the data table, that is why it is choking. 正如另一个人所指出的那样,你永远不会为数据表赋值,这就是为什么它会窒息。 Your query itself, by string concatenation will open you to SQL-Injection. 您的查询本身,通过字符串连接将打开您的SQL注入。 Parameterize it. 参数化它。 Finally, for your query, I would query all records for a given user ID, but get the user and password values based on only qualifying the user ID, not the password. 最后,对于您的查询,我将查询给定用户ID的所有记录,但是仅基于限定用户ID而不是密码来获取用户和密码值。 This way, if you have more than 1 row returned, it will indicate duplicate user accounts and should get special attention. 这样,如果您返回的行数超过1行,则表示会有重复的用户帐户,应该特别注意。 If it returns NO rows, then no such user. 如果它返回NO行,则没有这样的用户。 If it returns ONE row, then you can compare to the password entered and if matched, you have your correct user ID to run with. 如果它返回一行,那么您可以与输入的密码进行比较,如果匹配,您可以使用正确的用户ID。

starting with your 从你的开始

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");
   }
}

FINAL NOTE. 最后的说明。 You should also look into cleaning data especially before building SQL commands. 您还应该在构建SQL命令之前查看清理数据。 Never concatenate strings where users can manually enter data for SQL-Injection, parameterize them. 永远不要连接用户可以手动输入SQL注入数据的字符串,并对其进行参数化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM