簡體   English   中英

如何檢查我的程序是否與C#中的MSQL數據庫連接?

[英]how do i check if my program is connected with my MSQL database in C#?

您好,我是一名學生,我被困在零件上,我需要檢查問題是否與我的連接或我的代碼有關,請不要告訴我我的代碼有問題嗎?我應該使用哪種方式檢查MySql數據庫是否已連接? 是的,我停用了其余代碼以檢查其代碼。

 private void Btnlogin_Click_1(object sender, EventArgs e)
    {
        MySqlConnection con = new MySqlConnection("Data Source=localhost; user id = root; Password =''; Database = login; SslMode=none");
        Debug.WriteLine(con);
        /* MySqlDataAdapter sda = new MySqlDataAdapter("Select Count(*) from users where id='" + Txtusername + "' and pword='" + Txtpassword + "' ", con);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        if (dt.Rows[0][0].ToString() == "1")
        {

            this.Hide();

            main ss = new main();
            ss.Show();
        }
        else
        {
            MessageBox.Show("failed to login please check your username and password");

        }*/

嘗試這種方式:

using (MySqlConnection connection = new MySqlConnection(connectionString))
{
    try
    {
        connection.Open();
        using (MySqlCommand command = new MySqlCommand(query, connection))
        {
            command.CommandTimeout = 60 * 5;
            using (MySqlDataReader dataReader = command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    //Reading code..
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

關於此代碼的注釋:

1)擁有IDisposable對象時,請始終使用using語句

2) connection.Open(); 指令,將嘗試打開與數據庫的連接。 如果它不起作用,它將拋出異常,該異常將被此代碼中定義的try...catch

名稱空間專案名稱{公共部分類別登入:表格{SqlConnection cn = new SqlConnection(“此處為連接字串”);

    public login()
    {
        InitializeComponent();

    }



    private void freshrationpurchase_Load(object sender, EventArgs e)
    {

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cn.Open();
        cmd.CommandText = "select count( *) from user where id=@";
        SqlDataReader dr;
    dr=cmd.ExecuteReader();
        cn.Close();

    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM