简体   繁体   中英

Creating a sql connection in c#

I'm new to this site and also to programming. I am currently creating an inventory system via a point of sale. It uses modal and non-modal forms. My problem is tho, I'm working on the change password dialog which has to be connected to the database in order to overwrite the password field. The database i used is microsoft sql server management studio express. Here is what I have so far with the necessary comments. Please note that on the 'design' form, I have a combobox which is bounded to the database. Where did I go wrong?

private void ChangePwdButton_Click(object sender, EventArgs e)
{
  SqlConnection sqlconn = new SqlConnection();
  sqlconn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Gerald-   dean Martin\Documents\SQL Server Management Studio Express\Projects\BodyMates.mdf;Integrated Security=True;User Instance=True";
     sqlconn.Open();
    string oldpwd = txtOldPwd.Text;
    string newpwd = txtNewPwd.Text;
    string confirmNewPwd = txtConfirmNewPwd.Text;
    string sqlquery = "UPDATE [Employee] SET Pwd=@newpass where EmployeeCode=@empcode";
    SqlCommand cmd = new SqlCommand(sqlquery, sqlconn);
    cmd.Parameters.AddWithValue("@newpass", txtConfirmNewPwd.Text);
    cmd.Parameters.AddWithValue("@empcode", comboEmpCode.SelectedValue);
    //cmd.Parameters.AddWithValue("@pwd", txtNewPwd.Text);
    cmd.Connection = sqlconn;
    cmd.ExecuteNonQuery();
    SqlDataReader dr = cmd.ExecuteReader();             
    while (dr.Read())
    {
        if(txtOldPwd.Text == dr["pwd"].ToString() && (txtNewPwd.Text == txtConfirmNewPwd.Text))
        {
            if (comboEmpCode.SelectedIndex == 0)
            {
               string query = "UPDATE [Employee] SET Pwd = '" + txtConfirmNewPwd.Text + "'";
            }
        }

       // if ((txtNewPwd.Text == dr["newpwd"].ToString()) & (txtConfirmNewPwd.Text == (dr["confirmNewPwd"].ToString()))) { }
    }
   // MessageBox.Show("Password was changed Successfully!", "Password Change", MessageBoxButtons.OK, MessageBoxIcon.Information); 
}

You can use ExecuteNonQuery like cmd.ExecuteNonQuery(); It returns int value. Use it like this;

int i = cmd.ExecuteNonQuery();

And also ExecuteReader() works like this;

SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}", reader[0]));
        }

You can read returning data's column. Like first column reader[0] , second column reader[1] etc.

But before all this information, if you are new to programming, you can find a lot of book proposal and useful informations on Stackoverflow. Check these articles;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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