如何从数据库c#windows表单应用程序中检索数据?

时间:2015-02-04 11:56:35

标签: c# mysql database winforms

如何从MySQL数据库中检索或显示名称?我有一个数据库表,列为fID, USERNAME, PASSWORD and NAME。我使用表单1作为登录表单。现在我想在Form 2 Label上显示用户名。我怎么能这样做?

我被困在这里:

void log_in_btn_Click(object sender, EventArgs e)
{
    try
    {
            RF.openConnection("");
            RF.selectCommand("SELECT * FROM sign_up_table WHERE USERNAME = '" + txt_Username.Text + "' AND PASSWORD = '" + txt_Password.Text + "'");

            if (RF.result.Rows.Count == 1)
            {
                this.Visible = false;
                //here i want to display the name of the user but i dont know how so I'm just displaying the username.
                frm2.lbl_users_name.Text = txt_Username.Text;
                frm2.ShowDialog();
            }
            else
            {
                MessageBox.Show("Incorrect\nUsername or \nPassword!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            RF.closeConnection("");
    }
    catch (NullReferenceException ex)
    {
        MessageBox.Show(ex.Message);
    }
}

1 个答案:

答案 0 :(得分:0)

试试这段代码:

Public void log_in_btn_Click(object sender, EventArgs e)
{
    try
    {
        con.open();
        String strQuery = "SELECT * FROM sign_up_table WHERE USERNAME = '" + txt_Username.Text + "' AND PASSWORD = '" + txt_Password.Text + "'";
        sqlcommand cmd = new sqlcommand(strQuery,con);
        sqlDataAdapter adpt = new sqlDataAdapter(cmd);
        Datatable dt = new Datatable();
        adpt.Fill(dt);
        if (dt.Rows.Count == 1)
        {
            frm2.lbl_users_name.Text = dt.Rows[0]["NAME"].ToString();
            frm2.ShowDialog();
        }
        else
        {
            MessageBox.Show("Incorrect\nUsername or \nPassword!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        con.close();
    }
    catch (NullReferenceException ex)
    {
        MessageBox.Show(ex.Message);
    }
}