How to verify that you are connected to a MySQL database in C#?

后端 未结 2 1330
再見小時候
再見小時候 2021-01-23 18:53

I added the reference for the MySQL server in C#. I thought I have this code right. I know the connection values are right for testing. Here is my error:

{\"A network

相关标签:
2条回答
  • 2021-01-23 19:22

    Visit the MySQL download page entitled Download Connector/Net and proceed with the obvious. Note seek out the most recent download as this will age.

    Use the appropriate MySQL classes.

    using MySql.Data.MySqlClient;
    
    string connString = @"server=localhost;userid=drew;password=OpenSesame;database=stackoverflow";
    

    .

            long lRet = 0;
            using (MySqlConnection lconn = new MySqlConnection(connString))
            {
                lconn.Open();
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    cmd.Connection = lconn;
                    cmd.CommandText = @"select count(*) as theCount from batchQMetricsToUpdate where status=1";
                    lRet = (long)cmd.ExecuteScalar();
                }
            }
            return(lRet);
    

    Add References screenshot:

    0 讨论(0)
  • 2021-01-23 19:22

    You can do:

    using(SqlConnection connection = new MySqlConnection(connectionString))
    {
        try
        {
            conn.Open();
        }
        catch(SqlException ex)
        {
            switch(ex.Number) 
            { 
                case 18456: // Can't login
                    // Do something
                    break;
                default:
                    break;
            } 
        }
    }
    

    To get the complete list of codes run:

    SELECT * FROM master.dbo.sysmessages
    
    0 讨论(0)
提交回复
热议问题