Web. config configuration database connection

Source: Internet
Author: User
Tags connectionstrings

The first type:

Fetch connection string

String connstring = system.web.configuration.webconfigurationmanager.connectionstrings["SqlConnStr"]. ConnectionString;

Or

protected static string connectionString = configurationmanager.connectionstrings["Sqlconnstr"]. ConnectionString;

Web. config file: Add to </configSections> back

<connectionStrings>
<remove name= "LocalSqlServer"/>
<add name= "sqlconnstr" connectionstring= "User id=xx;password=xx;initial Catalog=database_name;data source=.\ Sqlxxxx "/>
</connectionStrings>

The second type:
Fetch connection string:

String myvar=configurationsettings.appsettings["ConnString"];

Web. config file: Add between <appsettings> and </appsettings>

<appsettings>
<add key= "connstring" value= "uid=xx;pwd=xx;database=batabase_name;server= (local)"/>
</appsettings>


It is said that the two are common, but the second is the new feature of Asp.net2.0, the second one is recommended.
In fact, I always have a question, two uid;pwd in a string, and the user ID; Password is equivalent.
According to the information I found on the internet can be interchangeable universal.

A seemingly more detailed explanation was found on the Internet:

The mechanism for connecting to a SQL Server database is not much different from the mechanism for connecting to access, except for changing the parameters in the Connection object and the connection string.

First, the namespaces used to connect to SQL Server are not "System.Data.OleDb", but "System.Data.SqlClient".

Next is his connection string, we introduce a parameter (note: The parameters are separated by semicolons):
"User Id=sa": The authenticated user name for the connection database is SA. He also has an alias "UID", so this sentence we can also write "Uid=sa".
"Password=": The authentication password for the connection database is empty. His nickname is "pwd", so we can write "pwd=".
Note here that your SQL Server must already have a username and password to log in, or you cannot log in in such a way. If your SQL Server is set to Windows logon, you do not need to use "User ID" and "password" here. Such a way to log in, and you need to use "TRUSTED_CONNECTION=SSPI" to log in.
"Initial Catalog=northwind": The data source used is the database "Northwind". His nickname is "database", this sentence can be written as "Database=northwind".
"Server=yoursqlserver": Use a server named "YourSQLServer". His nickname is "Data Source", "Address", "Addr". If you are using a local database and you have defined an instance name, you can write as " server= (local) \ instance name, or, if it is a remote server, replace "(local)" with the name or IP address of the remote server.
"Connect timeout=30": The connection time-out is 30 seconds.

In this case, the constructor used to establish the connection object is: SqlConnection.

Recently, I was looking at ASP. Web. config is very unclear, specifically from the network, MSDN collection, induction and collation for everyone to share.

The configuration of the connection string can be written in two ways in the Web. config of ASP.

<configuration>   <appSettings>      <add key= "connstr1" value= "Data source=.;i Nitial catalog=dbname;integrated security=true "/>      <add key=" connstr2 "value=" ... ">   </ appsettings>   <connectionStrings>      <add name= "CONNSTR3" connectionstring= "..."/>      <add name= "CONNSTR4" connectionstring= "..." providername= "System.Data.Sqlclient" </connectionstrings   ></configuration>

As shown in the code above: two methods are appsettings and connectionstrings

AppSettings:

① It was asp.net1.1, used in vs2003.

The ② is the equivalent of a key-value pair in the form, key and value. Not only can you save the connection string, but you can also store some configuration items. Where value includes information such as the database server address, user name and password, database name, and so on.

③ in appsettings, you can not use Providername= "System.Data ..." (but if you want to use it, just write it in value and pass it as a value)

④ in the background to take the value way with the code:

     String conn=system.configuration.configurationmanager.appsettings["ConnStr";]

ConnectionStrings:

① It is new in asp.net2.0.

The ② is also similar to the key-value pair, using name and ConnectionString, which generally saves the connection string.

③ can be used in connectionstrings, you can use ProviderName.

④ in the background code, the way to take the value:

     String conn=system.configuration.configurationmanager.connectionstrings["ConnStr"]. ConnectionString;
Other instructions:
①initial Catalog=database is the name of the database, according to the information collected from the network, the two seem to be completely generic, basically no difference.
     ②integrated Security Integrated Safety option setting, the recognized value is true, false, yes, no, and SSPI equivalent to true. When False, a user ID and password are specified in the connection. When True, the current Windows account credentials are used for authentication. Where SSPI is the security Supoort Provider interface is the secure support Provider interface, the Microsoft Security Support Provider Interface (SSPI) is a fully defined public API for authentication, information integrity, Integrated security services such as information privacy, as well as security-related services for all distributed application protocols. The Application Protocol designer can take advantage of this interface to obtain different security services without modifying the protocol itself. In the SQL Server database connection string, Integrated Security=sspi means using Windows authentication, which is to connect to SQL Server with the user running the current application, which is typically an anonymous user in IIS for a Web page.

since connectionstrings is a version 2.0, it's certainly better than appsettings :

Online says:

① can encrypt the connection string and use one of MS's encryption tools.
② can directly state the data source control without having to write code to read it and assign it to the control.
③ can easily replace the database platform, such as the Oracle database, just modify the ProviderName

ProviderName What is the role of it?

Let's take a look at the parameter values of the providername.

①providername= "System.Data.SqlClient"  ----instructions for using the MSSQLServer database ②providername= "System.Data.SqlLite"  ---- Description is using the Sqllite database ③providername= "System.Data.OracleClient"  ----instructions for using an Oracle database or providername= " System.Data.Oracle.DataAccess.Client "  ----Ibid ④providername=" System.Data.OleDb "   ----instructions for using an Access database

ProviderName can write without writing.

When do we use providername?

For example, we are now going to do a project that will be sold for two companies using: A and B. There is an element of uncertainty, and a uses SQL Server with Oracle,b.

So

① database: We need to build two libraries, one with Oracle and one with SQL Server.

② Program: We generally do not write two systems to let them use, we will definitely judge, first determine what database they are using, and then execute what kind of database script in the program.

③web.config Code:

<configuration>  <connectionStrings>    <add name= "connstr" connectionstring= "Data source=.;i Nitial catalog=mydb;integrated security=true "providername=" System.Data.SqlClient "/> </  Connectionstrings></configuration>
④ Program code: Make a judgment, if Providername= "System.Data.SqlClient" then execute SQL Server script, if providername= "System.Data.OracleClient" Oracle's database script is called.
public static readonly String connstr = system.configuration.configurationmanager.connectionstrings["ConnStr"]. Providername;public static string databasetype = system.configuration.configurationmanager.connectionstrings[" ConnStr "]. providername;public static int ExecuteNonQuery (CommandType commandtype, string commandtext, params System.data.oledb.oledbparameter[] parm) {    int num = 0;    if (DatabaseType = = "System.Data.SqlClient")    {        //Here Execute database script for Microsoft SQL Server    }    else if ( DatabaseType = = "System.Data.OracleClient")    {        //Here Execute Oracle's database script    }    return num;}
Common database Connection code (C #):
SqlConnection conn = new SqlConnection ("server= (local); Integrated security=sspi;database=pubs"); SqlConnection conn = new SqlConnection ("server= (local) \netsdk;database=pubs;integrated Security=sspi"); SqlConnection conn = new SqlConnection ("Data source=localhost;integrated security=sspi;initial catalog=northwind;"); SqlConnection conn = new SqlConnection ("Data source= (local); Initial catalog=xr;integrated security=sspi;persist Security Info=false;workstation Id=xurui;packet size=4096; “); SqlConnection myconn = new System.Data.SqlClient.SqlConnection ("Persist Security Info=false;integratedsecurity=sspi; Database=northwind;server=mysqlserver "); SqlConnection conn = new SqlConnection ("Uid=sa;pwd=passwords;initial catalog=pubs;data source=127.0.0.1; Connect timeout=900 ");

Web. config configuration database connection

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.