我们如何在C#.net中动态设置SQL连接字符串(Windows应用程序) [英] How we set SQL Connection string dynamically in C#.net(Windows Application)

查看:167
本文介绍了我们如何在C#.net中动态设置SQL连接字符串(Windows应用程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,

我正在使用C#.net开发我的Windows应用程序.在这里,我想将我的sql server 2008数据库与我的项目连接起来...

我的问题是如何在我的项目中动态设置sql连接字符串...

任何人都可以帮助我........



am developing my windows application using C#.net..here i want to connect my sql server 2008 database with my project...

My Problem is how to set sql connection string dynamically in my project...

Any one help me out of this........

推荐答案

好吧,请将连接字符串保存在web.config(或app.config)文件中.

添加类似内容:

Well by saving your connection string in a web.config (or app.config) file.

Add something similar:

<configuration>
  <connectionStrings>
  <clear />
    <add name="Target" connectionString="server=MYSERVER; Database=MYDB; Integrated Security=SSPI;" />
  </connectionStrings>
</configuration>




然后使用ConfigurationManager:
进行检索




Then retrieve it by using ConfigurationManager:

ConfigurationManager.ConnectionStrings["Target"].ConnectionString




您还需要引用System.Configuration库以使其起作用.

一个简单的




You also need to reference the System.Configuration library in order to make it work.

A simple

textBox1.Text = ConfigurationManager.ConnectionStrings["Target"].ConnectionString;



将显示您的连接字符串;)


希望对您有帮助

干杯!



Will show your connection string ;)


Hope it helps

Cheers!


您可以从服务器名称字符串构建连接字符串,并将其提供给您的SqlConnection对象.

You can build your connection string from server name string and give that to your SqlConnection object.

string constr = "Server=" + servername + ";database=" + dbname + ";integrated security=sspi";


创建一个类连接并在其中设置连接字符串..
然后,根据需要替换服务器名和数据库名.
Create a class for Connection and set connection string in that..
Then replace the servername and dbname when you want.


这篇关于我们如何在C#.net中动态设置SQL连接字符串(Windows应用程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆