How do I check if my C# — MySQL connection was successful or, if it was not, return why?

家住魔仙堡 提交于 2019-12-11 13:33:13

问题


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.



来源:https://stackoverflow.com/questions/6665953/how-do-i-check-if-my-c-sharp-mysql-connection-was-successful-or-if-it-was-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!