如何检查我的C# - MySQL连接是否成功,如果不是,返回为什么? [英] How do I check if my C# — MySQL connection was successful or, if it was not, return why?

查看:577
本文介绍了如何检查我的C# - MySQL连接是否成功,如果不是,返回为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这一块C#代码。基本上,我想做的是某种机制来检查,首先,我的SQL服务器的用户和密码组合是否正确,然后检查数据库是否存在。

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.

连接字符串如下:

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

我试图达到的解决方案是可以检查异常抛出,错误的密码,错误的用户,未找到数据库等。我已经看到在一些地方使用DbConnectionStringBuilder,但我不知道我应该如何使用它。

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.

推荐答案

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

Sql Server的完整列表可通过运行

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

SELECT * FROM master.dbo.sysmessages

这篇关于如何检查我的C# - MySQL连接是否成功,如果不是,返回为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆