连接到数据库 C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18562348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:35:20  来源:igfitidea点击:

connect to database c#

c#databasedatabase-connection

提问by 0xPwn

I'm trying to connect to a DB on a server using C# but with no luck.

我正在尝试使用 C# 连接到服务器上的数据库,但没有运气。

I tried using this:

我尝试使用这个:

public static string m_ConnectionString =
    @"Network Library=dbmssocn; Data Source=*server ip*,*port*; database=*db name*; " +
    @"User id=*db username*; Password=*db pass*;";
public static SqlConnection myConnection = new SqlConnection(m_ConnectionString);

I get this error:

我收到此错误:

Connection Timeout Expired. The timeout period elapsed while attempting to consume the pre-login handshake acknowledgement. This could be because the pre-login handshake failed or the server was unable to respond back in time. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=9343; handshake=5654;

连接超时已过期。尝试使用登录前握手确认时超时时间已过。这可能是因为登录前握手失败或服务器无法及时响应。尝试连接到此服务器所花费的时间为 - [Pre-Login] 初始化 = 9343;握手=5654;

when I used myConnection.Open();

当我使用 myConnection.Open();

I tried also to set the timeout to int.MaxValueand it didn't work.

我也尝试将超时设置为int.MaxValue,但没有用。

回答by Olivier Jacot-Descombes

A very good source for SQL Server (and many other) connection strings is http://www.connectionstrings.com/sql-server/. Depending whether you are connecting through ODBC, OLE DB or Native Client, you have to choose another connection string.

SQL Server(和许多其他)连接字符串的一个很好的来源是http://www.connectionstrings.com/sql-server/。根据您是通过 ODBC、OLE DB 还是 Native Client 进行连接,您必须选择另一个连接字符串。

Try

尝试

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;

or

或者

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

There are a lot of options to choose from, depending on the exact SQL Server version, the security type and many more.

有很多选项可供选择,具体取决于确切的 SQL Server 版本、安全类型等等。



UPDATE

更新

First you have to choose a data access technology.

首先,您必须选择一种数据访问技术。

  • .NET Framework Data Provider for SQL Server(SqlConnection), Is the preferred way of accessing the SQL Server from .NET code. (See When to use the SQL Native Clientfor a comparison)

  • Native Client: Is a very fast way of accessing the SQL Server and supports the new features, as it accesses the SQL Server TDS protocol directly and works for non .NET code. It should be preferred for non .NET code.

  • ODBC: Is relatively fast and compatible to a lot of different databases. Choose this one if the data base type might change in future or if you are accessing "exotic" databases.

  • OLEDB: For SQL Server it is relatively slow and will be depreciated by Microsoft.

  • .NET Framework Data Provider for SQL Server( SqlConnection),是从 .NET 代码访问 SQL Server 的首选方式。(请参阅何时使用 SQL Native Client进行比较)

  • Native Client:是一种非常快速的访问 SQL Server 的方式并支持新功能,因为它直接访问 SQL Server TDS 协议并且适用于非 .NET 代码。它应该是非 .NET 代码的首选。

  • ODBC:相对较快并且兼容许多不同的数据库。如果数据库类型将来可能会发生变化,或者您正在访问“异国情调”数据库,请选择此选项。

  • OLEDB:对于 SQL Server,它相对较慢,并且会被 Microsoft 折旧。

Then you have to choose between SQL Server Authentication(User/Password) and Windows Authentication. I would choose the latter if possible. With Windows Authentication the SQL-Server assumes that if you logged in successfully to Windows you are a trusted user. The Windows user name will then be mapped 1 to 1 to a SQL-Server user. Of course this user then must still have been granted the rights requested for the operations that he will perform on the SQL Server (like SELECT, INSERT, UPDATE, DELETE). If the DBA didn't install Windows Authentication, you will have to go with uid/pwd.

然后您必须在SQL Server Authentication(User/Password) 和Windows Authentication之间进行选择。如果可能,我会选择后者。使用 Windows 身份验证,SQL-Server 假定如果您成功登录到 Windows,您就是一个受信任的用户。然后,Windows 用户名将一一映射到 SQL-Server 用户。当然,此用户必须仍被授予他将在 SQL Server 上执行的操作(如 SELECT、INSERT、UPDATE、DELETE)所请求的权限。如果 DBA 没有安装 Windows 身份验证,则必须使用 uid/pwd。

This worked for me:

这对我有用:

string connectionString =
    "Data Source=192.168.123.45;Initial Catalog=MyDatabase;Integrated Security=SSPI;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
    using (SqlCommand command = new SqlCommand(
                 "SELECT Region FROM dbo.tlkpRegion WHERE RegionID=30", connection)) {
        connection.Open();
        string result = (string)command.ExecuteScalar();
        MessageBox.Show("Region = " + result);
    }
}

回答by Marko Gre?ak

I think that Data Source=*server ip*,*port*;should be Data Source=*server ip*:*port*;, replacing ,with :. But if the port is not specific, I don't think you really need it. Also you're not defining a driver, I don't know it this works without it.

我认为Data Source=*server ip*,*port*;应该是Data Source=*server ip*:*port*;,替换,:. 但是如果端口不是特定的,我认为你真的不需要它。此外,您没有定义驱动程序,我不知道没有它就可以工作。

Also a advice: look up LINQ to SQLor ADO.NET Entity Data Model. Those can really simplify use of databases and using LINQ you can write a query inside code which is a lot similar to sql and Visual Studio also helps with intellisense so you don't have to remember all table and column names.

还有一个建议:查找LINQ to SQLADO.NET Entity Data Model。这些可以真正简化数据库的使用,并且使用 LINQ 您可以在代码中编写一个与 sql 非常相似的查询,Visual Studio 也有助于智能感知,因此您不必记住所有表和列名称。