此代码显示“CommandText尚未初始化”

时间:2017-11-17 14:47:25

标签: c# sql-server database

我想检查数据库中的ManagerUsername和ManagerEmail,并显示一个消息框,向用户显示他们的密码。但是当我执行代码时,它向我显示:

  

“commandtext尚未初始化”

所以我想知道如何修复我的代码以显示我想要的内容。还有一种方法可以提高我的代码以提高工作效率

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Cybertronics
{
    public partial class passwordRecovery : Form
    {
        int pin = 0;
        private int _failedAttempts = 0;

        public passwordRecovery()
        {
            InitializeComponent();
        }

        private void passwordRecovery_Load(object sender, EventArgs e)
        {
            lblAttempt.Visible = false;
        }

        private void btnBackLogin_Click(object sender, EventArgs e)
        {
            loginFrm loginForm = new loginFrm();
            this.Hide();
            loginForm.Show();
        }

        private void btnSubmitEmail_Click(object sender, EventArgs e)
        {
            try
            {
                string emailAddress = txtEmail.Text;
                string username = txtManagerUsername.Text;
                string password = "ChangeMe";
                CyberDatabase db = new CyberDatabase();
                db.OpenConnection();
                SqlCommand cmd = new SqlCommand();
                SqlDataReader reader;

                cmd.Parameters.AddWithValue("@ManagerUsername", username);
                cmd.Parameters.AddWithValue("@ManagerEmail", emailAddress);
                db.SetSqlCommand(cmd);
                reader = db.Select();

                cmd.CommandText = "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = @ManagerUsername and ManagerEmail = @ManagerEmail";
                db.SetSqlCommand(cmd);
                reader = db.Select();

                if (reader.HasRows)
                {
                    reader.Read();
                    SqlCommand passwordUpdate = new SqlCommand();
                    passwordUpdate.CommandText = "UPDATE tblManagers SET ManagerPassword=@Password WHERE ManagerUsername=@ManagerUsername and ManagerEmail=@ManagerEmail";
                    db.SetSqlCommand(passwordUpdate);
                    MessageBox.Show("your new password is:" + password);
                }
                else
                {
                    if (pin != 21)
                    {
                        _failedAttempts++;
                        MessageBox.Show("Wrong password or username fail to login. you have" + (3 - _failedAttempts) + " attempts more.", "EPIC FAIL", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                        if (_failedAttempts == 3)
                        {
                            Application.Exit();
                        }
                    }
                }
            }
            catch (SqlException sql)
            {
                CyberMethods.DisplayErrorMessage(sql.Message);//error message from cybermethods class for DB
            }
            catch (Exception exc)
            {
                CyberMethods.DisplayErrorMessage(exc.Message);//error message from cybermethods class
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的代码非常凌乱和混乱。这很容易出错。查看以下示例代码以获取最佳实践。

using (connection)
using (SqlCommand command = new SqlCommand(
  "SELECT ManagerUsername from tblManagers WHERE ManagerUsername = @ManagerUsername and ManagerEmail = @ManagerEmail",
  connection))
{
    connection.Open();

    using (SqlDataReader reader = command.ExecuteReader())
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }

    } 
}

您有多个查询语句。对于职责分离原则,我建议您分别设置3个功能并分别调用它们。

明智的做法是先保持连接打开,然后在所有操作完成后关闭。

用于解决错误

在您的第一个db.SetSqlCommand(cmd);之前,只需添加查询语句

cmd.CommandText = "select ....." ;