如何在c#中创建单独的连接字符串? [英] how to make separate Connection String in c# ?

查看:68
本文介绍了如何在c#中创建单独的连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨...

我是初学者

我在c#winform中制作拼贴画项目

i想要一个单一的课程包含SqlConnection字符串的代码以及用于打开Connection的代码!

我希望以所有形式访问此连接...





连接应该在整个应用程序中打开一次并在关闭应用程序后关闭..





提前谢谢!

Hi...
I''m beginner
I''m making collage project in c# winform
i want a single class that contain the code for SqlConnection string as well as for opening Connection !
and i want to access this connection in all form ...
.
.
And the Connection should open once in whole Application and close after closing the application..


Thanks in advance!

推荐答案

这是错误的做法。您应该在访问数据库之前立即打开连接,然后立即关闭它。在应用程序运行期间保持连接打开是非常糟糕的做法,并且在多用户应用程序的情况下会严重影响性能和安全性。
That is the wrong way to do it. You should open your connection immediately before accessing the database, and close it immediately afterwards. Leaving the connection open all the time your application is running is very bad practice, and in the case of multi-user applications can seriously impact performance and security.


请参阅下面给出的链接:

代码项目问题:单独的Sql连接class

请参考以下链接创建数据访问组件:

在C#中为SQL Server创建DataAccess组件
Refer link given below:
Code Project Question: Sql Connection in seperate class
Refer link given below to create a data access component:
Creating DataAccess Component for SQL Server in C#


尝试使用Static类和变量。





Try using Static class and variables for this.


public static class DataAccessClass
{

    static SqlConnection objConn = new SqlConnection();


    public static SqlConnection MyConnection
    {
        get { return objConn; }

    }

    public static void OpenConnection()
    {
        string ConnectionSring = "MYCONNECTIONSTRING";
        objConn.ConnectionString = ConnectionSring;
        objConn.Open();
    }



    public static void CloseConnection()
    {
        objConn.Close();
    }



}







这是我在这里描述的非常基本的结构。

我没有做你的功课所以你必须自己添加你的代码和异常处理。

一旦你发起连接






This is very basic structure i am describing here.
I am not doing your homework so you have to add your code and exception handling by yourself.
Once you initiate the connection

DataAccessClass.OpenConnection();





您的连接在整个申请期间都是开放的,您不必再打开它。



我建议你必须永远不要执行此操作,因为将Connection打开是不好的做法。





更好的方法是打开连接执行数据库操作并立即关闭。


这篇关于如何在c#中创建单独的连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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