0

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

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

但是,即使使用这条路线,我也会得到相同的 sql 异常。对我来说,这说明 Visual Studio 中的某些内容设置不正确,但我可能是错的。

我正在使用以下代码连接到服务器上的数据库(使用 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 中查询它。

4

2 回答 2

2

我猜它找不到服务器。鉴于大多数路由器/调制解调器的默认配置,我怀疑这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
    }
}
于 2013-05-08T17:20:16.420 回答
0

好了,大家的答案就到这里了!!!

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

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

于 2013-05-14T17:37:51.327 回答