简体   繁体   English

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

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

Hello I'm a student and I'm stuck on a part I need to check if the problem is with my connection or with my code please don't tell me if something is wrong with my code just help me in the right direction what kind of way should I use to check if my MySql database is connected? 您好,我是一名学生,我被困在零件上,我需要检查问题是否与我的连接或我的代码有关,请不要告诉我我的代码有问题吗?我应该使用哪种方式检查MySql数据库是否已连接? And yes I deactivated the rest of the code to check if its the code. 是的,我停用了其余代码以检查其代码。

 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");

        }*/

Try this way: 尝试这种方式:

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());
    }
}

Notes about this code: 关于此代码的注释:

1) Always use using statements when you have IDisposable objects 1)拥有IDisposable对象时,请始终使用using语句

2) The connection.Open(); 2) connection.Open(); instruction, will try to open the connection to your DB. 指令,将尝试打开与数据库的连接。 If it won't work, it will throw and exception which will be catched by the try...catch defined in this code 如果它不起作用,它将抛出异常,该异常将被此代码中定义的try...catch

namespace projectname { public partial class login : Form { SqlConnection cn = new SqlConnection("connection string here"); 名称空间专案名称{公共部分类别登入:表格{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