如何检查我的程序是否与C#中的MSQL数据库连接?

时间:2018-09-18 07:34:52

标签: c# mysql

你好,我是学生,我被困在零件上,我需要检查问题是否与我的连接或我的代码有关,请不要告诉我我的代码是否有问题,请仅在正确的方向应该使用哪种方式检查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");

        }*/

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

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)拥有using个对象时,请始终使用IDisposable条语句

2)connection.Open();指令将尝试打开与数据库的连接。如果不起作用,它将抛出异常,此代码中定义的try...catch将捕获该异常

答案 1 :(得分:0)

命名空间项目名称 {     公共部分课程登录:表格     {         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();

    }
}

}