使用类存储sql连接字符串 [英] To use a class to store sql connection string

查看:81
本文介绍了使用类存储sql连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个ac#项目,我有一个sql数据库,我用每种形式将其连接到数据库,如何将连接字符串存储在一个类中并按需使用它

i m doing a c# project and i have sql database,in each form i hv to connect to the database,how can i store the connection string in a class and use it as required

推荐答案

您不必这样做.您可以并且应该使用System.Configuration命名空间:

You don''t have to. You can and should use the System.Configuration namespace:

var connectionString = ConfigurationManager.ConnectionStrings["CONNECTIONSTRINGNAME"];



如果您打算通过类属性访问此值,则可以执行以下操作:



If you''re intent on accessing this value through a class property, you can do the following:

public class Foo
{
    public static string ConnectionString
    {
        get { return ConfigurationManager.ConnectionStrings["CONNECTIONSTRINGNAME"]; }
    }
}


如果您与SQL有连接,则连接字符串将保存在设置文件中,您可以在需要时按以下方式访问它:

If you have a connection to SQL, the connection string will be saved in setting file, You can access it like this whenever you need it:

Properties.Settings.Default.ConncectionString


对于存储连接字符串,为什么要使用整个类.
它只需要一个变量
For Storing Connection String why are you using whole Class.
It requires Just one variable
String ConnectionString="Enter Your Connection String Here";


之后,在需要的地方使用该变量.:)


After that Use that Variable Where you Want.:)


这篇关于使用类存储sql连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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