Connect to various databases

Source: Internet
Author: User
Tags how to connect to sql server connection reset

The connection of various databases is described in detail here.
Http://www.connectionstrings.com/

 

 

Example: String strconn = "Data Source =.; initial catalog = database name; Integrated Security = ture"
String strconn = "Data Source =.; initial catalog = database name; Integrated Security = false"; user id = sa; passwrod = 123;
String strconn = "Server =.; database = database name"; user id = sa; Password = 123;

1. Data Source
The data source can also be called a server.
"Data Source" can be replaced by the following strings: "server", "Address", "ADDR", and "network address ".
Local Data Source: Data Source =./sqlexpress, data source = (local)/sqlexpress

2. Initial catalog
Database Name
Initial catalog can be replaced by the following two strings: "Database"
3. Integrated Security
"Integrated Security" can be written as "trusted_connection"
If this parameter is set to true, the current Windows authentication is used.
When the value is false, you must specify the user name and password in the connection (even if there is a user ID and password in the connection string, it does not work !)
Integrated security can be set to: True, false, yes, no, which is easy to understand. In addition, it can be set to: sspi, which is equivalent to true.

 

 

 

// SQL Server Authentication connection string
Private string connstrsqlserver = "Server = server name; uid = login name; Pwd = login password; database = database name ";

 

// Windows Authentication connection string
Private string connstrwindows = "Server = server name; database = database name; trusted_connection = sspi ";

 

// Access the SQL Server 2008 database using sqlclient in C # code
//. NET Framework data provider for SQL Server standard syntax
Data Source = myserveraddress; initial catalog = mydatabase; user id = myusername; Password = mypassword;

 

// Another standard method for. NET Framework data provider for SQL Server
Server = myserveraddress; database = mydatabase; user id = myusername; Password = mypassword; trusted_connection = false;

 

//. NET Framework data provider for SQL Server Trust connection statement
Data Source = myserveraddress; initial catalog = mydatabase; Integrated Security = sspi;

 

//. NET Framework data provider for SQL Server
Server = myserveraddress; database = mydatabase; trusted_connection = true;

 

The SQL Server. NET data provider connection string contains a set of attribute name/value pairs. Each attribute/value pair is separated by a semicolon. Propertyname1 = value1; propertyname2 = value2; propertyname3 = value3 ;..... similarly, the connection string must contain the SQL server instance name: Data Source = servername; use the local SQL Server (localhost). If you want to run it on a remote server, the correct server should be assigned to the data source attribute in the example object. In addition, you must specify either of the two supported authentication methods (Windows Authentication and SQL Server Authentication. Windows Authentication uses Windows login user identity to connect to the database, and SQL authentication requires that the SQL Server user ID and password be explicitly specified. To use Windows authentication, you must include the Integrated Security attribute in the connection string: Data Source = servername; Integrated Security = true;

By default, the Integrated Security attribute is false, which means Windows authentication is disabled. If the value of this attribute is not explicitly set to true, the connection uses SQL Server Authentication. Therefore, the SQL Server user ID and password must be provided. The integrated security attribute can recognize other values only sspi (Security Support Provider Interface, Security Support Provider Interface ). all Windows NT operating systems, including Windows NT 4.0, 2000, and XP, support sspi. It is the only interface that can be used for Windows authentication. It is equivalent to setting the value of integrated security to true.

In Windows Authentication mode, SQL server uses the Windows security subsystem to verify the validity of user connections. Even if the user ID and password are explicitly specified, SQL server does not check the user ID and password in the connection string. Because only Windows NT, 2000, and XP support sspi, if you are using these operating systems, you can only use Windows integrated security policies to connect to SQL Server. No matter which operating system is used, when using SQL Server Authentication, you must specify the user ID and password in the connection string: Data Source = servername; user id = donaldx; Password = unbreakable

By default, SQL Server. NET data provider connects to the default database of the specified user. When creating a user in the database, you can set the default database of the user. In addition, you can change your default database at any time. For example, the default database of the system administrator is master. To connect to different databases, specify the Database Name: Data Source = servername; Integrated Security = sspi; initial catalog = northwind

Each authentication method has its advantages and disadvantages. Windows Authentication uses a single user information library source. Therefore, you do not need to configure users for database access separately. The connection string does not contain the user ID and password, which eliminates the risk of exposing the user ID and password to unauthorized users. Users and their roles can be managed in Active Directory without explicitly configuring their properties in SQL Server. The disadvantage of Windows authentication is that it requires the user to connect to SQL Server through the Secure Channel supported by the Windows security subsystem. If the application needs to connect to SQL Server through an insecure network (such as the Internet), Windows authentication will not work. In addition, this authentication method also partially transfers the responsibility for managing database access control from the DBA to the system administrator, which may be a problem in the identified environment. In general, some aspects will be enhanced to use Windows authentication when designing common applications. Most companies' databases reside on robust Windows server operating systems that support Windows authentication. The separation of the data access layer and the data presentation layer also promotes the application of data access code encapsulated in the middle layer component idea. The middle layer component usually runs in the internal network with a database server. In this design, you do not need to establish a database connection through an insecure channel. In addition, Web Services also greatly reduce the need to directly connect to databases in different domains.

Database Connectivity has developed into a standard aspect of application development. Database connection strings are now a standard prerequisite for each project. I found that in order to find the required syntax, I often need to copy the connection string from another application or perform a search. This is especially true when interacting with SQL Server because it has too many connection string options. Now let's take a look at the many aspects of the connection string.

Connection string

During Object Instantiation or establishment, database connection strings are passed to necessary objects through attributes or methods. The format of the connection string is a list of key/value parameter pairs divided by semicolons.ListContains an example in C # to illustrate how to connect to SQL Server by creating a sqlconnection object (the actual connection string is allocated through the connectionstring attribute of the object ).List BWhich includes the VB. NET version.

ListA

String cstring = "Data Source = server; initial catalog = dB; user id = test; Password = test;"; sqlconnectionconn = new sqlconnection (); Conn. connectionstring = cstring; Conn. open ();

ListB

Dim cstring as string cstring = "Data Source = server; initial catalog = dB; user id = test; Password = test ;"

Dim conn as sqlconnection = new sqlconnection () Conn. connectionstring = cstring conn. open ()

The connection string specifies the database server and database, and the username and password required to access the database. However, this format does not apply to all database interactions. It does have many available options, many of which have synonyms.

With data source, initial catalog, user ID, password, and other elements, the following options are available:

 

    • Application name(Application name ):The name of the application. If it is not specified, its value is. Net sqlclient data provider ).
    • Attachdbfilename/Extended Properties(Extended attributes )/Initial file name(Initial file name ):Name of the main file that can be connected to the database, including the full path name. The database name must be specified with the keyword database.
    • Connect timeout(Connection timeout )/Connection timeout(Connection timeout ):The length (in seconds) of a connection to the server before termination. The default value is 15.
    • Connection lifetime(Connection survival time ):When a connection is returned to the connection pool, its creation time is compared with the current time. If the time span exceeds the validity period of the connection, the connection will be canceled. The default value is 0.
    • Connection Reset(Connection Reset ):Indicates whether a connection is reset when it is removed from the connection pool. A pseudo-valid server does not need to run back and forth after obtaining a connection. The default value is true.
    • Current Language(Current language ):The name of the SQL Server language record.
    • Data Source(Data Source )/Server(Server )/Address(Address )/ADDR(Address )/Network Address(Network address ):The name or network address of the SQL server instance.
    • Encrypt(Encrypted ):When the value is true, if an authorization certificate is installed on the server, SQL server uses SSL encryption for all data transmitted between the client and the server. The accepted values include true, false, Yes, and no ).
    • Enlist(Registration ):Indicates whether the connection pool program automatically registers the connection in the current transaction context of the Creation thread. The default value is true.
    • Database(Database )/Initial catalog(Initial cataloguing): Name of the database.
    • Integrated Security(Integrated Security )/Trusted connection(Trusted connection ):Indicates whether Windows authentication is used to connect to the database. It can be set to "true", "false", or "true-to-peer" sspi. Its default value is "false.
    • Max pool size(Maximum capacity of the Connection Pool ):The maximum number of connections allowed by the connection pool. The default value is 100.
    • Min pool size(Minimum capacity of the Connection Pool ):The minimum value of the number of connections allowed by the connection pool. The default value is 0.
    • Network Library(Network library )/Net(Network ):The network library used to establish a connection to an SQL server instance. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol/RPC), dbmsvinn (Banyan Vines), dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP ). The dynamic Connection Library of the Protocol must be installed to an appropriate connection. The default value is TCP/IP.
    • Packet Size(Packet size ):The size of the network packet used to communicate with the database. The default value is 8192.
    • Password(Password )/PWD:The password corresponding to the account name.
    • Persist Security info(Keep security information ):Used to determine whether security information is available after a connection is established. If the value is true, sensitive data such as the user name and password is available, and false data is unavailable. Resetting the connection string will reconfigure the values of all connection strings, including passwords. The default value is false.
    • Pooling(Pool ):Determine whether to use the connection pool. If the value is true, the connection will be obtained from the appropriate connection pool, or, if necessary, the connection will be created and then added to the appropriate connection pool. The default value is true.
    • User ID(UserID):The account name used to log on to the database.
    • Workstation ID(WorkstationID):The name of the workstation that connects to SQL Server. The default value is the name of the local computer.

       

       

      Some preliminary experiences after solving some basic problems during SQL server connection

      The student made a question bank system, using ASP applications written in C #, and SQL Server2000 for the database. An error occurs when it is placed on the server. After repeated adjustments, we found the solution, which is actually very simple. Looking back, I found that my lack of understanding about the SQL server connection statements and user permissions. Next I will share some of my experiences and relevant information I found on the Internet, so that it is superficial to learn from later users.
      1. SQL server connection method

      Taking the local server (localhost) and database (northwind) as an example, you can use the following Connection Methods: sqlconnection conn = new sqlconnection ("Server = localhost; Integrated Security = sspi; database = northwind "); sqlconnection conn = new sqlconnection (" Data Source = localhost; Integrated Security = sspi; initial catalog = northwind ;"); sqlconnection conn = new sqlconnection ("Data Source = localhost; initial catalog = northwind; Integrated Security = sspi; persist Security info = false; workstation id = xurui; packet size = 4096; "); sqlconnection myconn = new sqlconnection (" Persist Security info = false; Integrated Security = sspi; database = northwind; server = localhost "); sqlconnection conn = new sqlconnection ("uid = sa; Pwd = ***; initial catalog = northwind; Data Source = localhost; Connect timeout = 900 ");

      TIPS:

      A. server, database, data source, and initial catalog pairs can be used to replace each other. B. the default value of integrated security is false. UID and PWD must be provided to log on to the database as an SQL Server user. If it is set to true, yes, or sspi, UID and PWD cannot appear, log on to the database in the Windows user province. It is strongly recommended that the latter form be used for higher security. C. Integrated Security and persist Security info appear at the same time. The latter is set to false to ensure information security.

      For more string connection instructions, see msdn: http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpref/html/frlrfsystemdatasqlclientsqlconnectionclassconnectionstringtopic. asp

      There should be no problem after writing the connection string skillfully. I am looking at other people's programs. To tell the truth, some things are really unclear. But after the connection fails, you have to solve it. Therefore, you must understand the meaning of these keywords and modify them before testing.

      2. SQL Server user settings I. Use the connection string sqlconnection conn = new sqlconnection ("uid = sa; Pwd = ***; initial catalog = northwind; Data Source = localhost; connect timeout = 900 "); error: User" sa "Login Failed, no trusted SQL server connection information found solution: cause: the SQL Server authentication method must be set to a mix of SQL Server Authentication and Windows Integration authentication. If you only set it to the latter method, the problem will be solved as described above: run the SQL Server Enterprise Manager, click the server, select Properties from the context menu, and select security, change the authentication method. Question 2: Use the connection string sqlconnection conn = new sqlconnection ("Data Source = localho St; Integrated Security = sspi; initial catalog = northwind; "); error: User" computername \ iwam_servername "login failure cause: the SQL Server login user does not include iwam_servername solution: run the SQL Server Enterprise Manager, click the server, select Security, select login, add iwam_servername to the new login, and assign corresponding permissions. For example, you can only access the northwind database, set the database role to public and db_owner.

      3. Connection Security

      It is best to use sspi integrated security to connect to the database, while SA user connection may pose security risks. I think it is mainly because when installing SQL Server, the SA password is often set to be empty for access convenience. Once a hacker makes SA an administrator, all access permissions to the system can be obtained. For database security, you can set the SQL server access user to pass the Windows integrated verification, set the SA security password, and enhance the database security. Of course, after being set to Windows integration verification, the database performance and access flexibility will inevitably be affected. The administrator can set different verification methods for each database, instead of setting SQL server in a unified manner.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.