How do I check if my C# — MySQL connection was suc

2019-08-07 04:09发布

问题:

I am struggling a bit with this piece of C# code. Basically, what I'm trying to do is some kind of mechanism to check if, in first place, the user and password combination for my SQL server was correct, and then, check if the database exists.

The connection string would be like this:

connectionString = 
   "database=test;server=localhost;uid=" + usr.Text + ";pwd=" + pwd.Text;

The solution I'm trying to reach is one that can check the exception thrown and tell if it's about a wrong password, a wrong user, not found database, etcetera. I've seen the use of DbConnectionStringBuilder in some places but I'm not sure of how I should use it.

回答1:

   string connectionString = "database=test;server=localhost;uid=" + usr.Text + ";pwd=" + pwd.Text;
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
     try
     {
       conn.Open();
     }
     catch (SqlException ex)
     {
       switch (ex.Number) 
       { 
         case 4060: // Invalid Database 
          ....
          break;
         case 18456: // Login Failed 
          ....
          break;
         default:
          ....
          break;
       } 
     }
   }

The full list of Sql Server exception numbers can be found by running

SELECT * FROM master.dbo.sysmessages


回答2:

DbConnection.Open() will fail with invalid credentials.