开发者

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different 开发者_Go百科databases depending on which I point it to.

So how can I manually create the connection string? I am using SQL Server 2005.


Step 1: Go to connectionstrings.com and find the proper format for your database.

Step 2: Plug in the appropriate values to the connection string.

Step 3: Pass that string to the constructor of SqlConnection.

I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:

 SqlConnection sqlConn = new SqlConnection(
     ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);


I don't see where the connection string is "compiled".

In the code

SqlConnection con = new SqlConnection(
    ConsoleApplication1.Properties.Settings.Default.masterConnectionString)

ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.


for SQL Server format of the connection string is

"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"

save this connection string in a string variable and use with connection object.

either way you can add in web.config file.

<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address;       Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>

you can change the provider as needed by you.

then in code behind file access this particular connection string using configuration manager.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜