繁体   English   中英

在c#中连接到SQL Server时出现未知错误

[英]Unknown Error Connecting To SQL Server in c#

让我为这篇文章添加一个快速解释:

我正在使用visual studio,如果我创建了与数据库的连接,它就可以工作。 我可以通过数据库设计器(您看到表并可以创建新查询的那个)查询数据库,并正确地处理数据。

但是,即使使用此路由,我也得到相同的sql异常。 对我来说,这说明视觉工作室中的某些东西没有正确设置,但我可能是错的。

我使用以下代码连接到我的服务器上的数据库(使用System.Data.SqlClient;在顶部):

SqlConnection thisConnection = new SqlConnection();
thisConnection.ConnectionString = 
                              "Data Source=192.168.0.0,1433;" +
                              "Initial Catalog=test-db;" +
                              "User Id=UserName;" +
                              "Password=Password;";
thisConnection.Open();

我收到以下错误:

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, TdsParserState state) 
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, TdsParserState state) 
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() 
at System.Data.SqlClient.TdsParser.Connect(String host, SqlInternalConnection connHandler, Int32 timeout) 
at System.Data.SqlClient.SqlInternalConnection.OpenAndLogin() 
at System.Data.SqlClient.SqlInternalConnection..ctor(SqlConnection connection, Hashtable connectionOptions) 
at System.Data.SqlClient.SqlConnection.Open() 
at InventoryControl.Login.validUserName() 
at InventoryControl.Login.LoginButton_Click(Object sender, EventArgs e) 
at System.Windows.Forms.Control.OnClick(EventArgs e) 
at System.Windows.Forms.Button.OnClick(EventArgs e) 
at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam) 
at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam) 
at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain) 
at System.Windows.Forms.Application.Run(Form fm) 
at InventoryControl.Program.Main()

如果你有任何想法如何解决这个问题,将不胜感激!

例外情况如下:

System.Data.SqlClient.SqlError: SQL Server does not exist or access denied

但是我很肯定我有这个服务器的权限,因为我可以访问它并在visual studio中查询它。

我猜它找不到服务器了。 鉴于大多数路由器/调制解调器的默认配置,我怀疑192.168.0.0是您正在寻找的IP。 如果它在您的本地计算机上,请使用localhost127.0.0.1或您的计算机名称(例如hans-pc )。 如果它在另一台计算机上,则需要确保您具有正确的IP,并且它已配置为在防火墙和SQL Server配置管理器中进行远程访问(启用TCP / IP和/或命名管道协议)。

此外,您可以为该字符串中的属性使用一些别名来缩短它:

server=192.168.0.0;database=test-db;user id=UserName;password=Password
                                                                      ↑
                                      Make sure no trailing semicolon ┘

我删除了端口,因为1433是SQL Server的默认端口。

要获取有关异常的更多信息,请尝试以下代码:

try
{
   ...
   thisConnection.Open();
   ...
}
catch (SqlException ex)
{
    for (int i = 0; i < ex.Errors.Count; i++)
    {
        Console.WriteLine(ex.Errors[i].ToString());
        // or output them wherever you need to see them
    }
}

好吧所以这里是大家的答案!

模拟器设置不正确...这与代码无关! 您需要设置模拟器以连接到互联网,如果使用移动模拟器,请参阅此链接:

http://www.xdevsoftware.com/blog/post/Enable-Network-Connection-Windows-Mobile-6-Emulator.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM