简体   繁体   English

C#+ MySQL连接

[英]C# + MySQL Connections

I am currently working on a C# (.NET) project which connects to a MySQL Community Server database and runs some queries. 我目前正在研究一个C#(.NET)项目,该项目连接到MySQL Community Server数据库并运行一些查询。 There are currently 4 classes which use their own MySQLConnection object (I'm using the MySQL .NET connector), in order to connect to the database. 当前有4个类使用它们自己的MySQLConnection对象(我​​正在使用MySQL .NET连接器),以便连接到数据库。

Is this good practice, or should I use one 'global' (static?) connection? 这是一种好的做法,还是我应该使用一个“全局”(静态)连接? Using one single connection is kind of against my habits of structuring the code. 使用单个连接有点违反我编写代码的习惯。 Not a big fan of 100000 objects working with one shared static field. 对一个共享静态字段使用100000个对象不是一个大粉丝。 I bet it's against most programmers' views too. 我敢打赌,这也违反了大多数程序员的观点。

I also noticed that once I call connection.Close(), the connection does not necessarily get closed. 我还注意到,一旦调用connection.Close(),连接并不一定会关闭。 Trying to .Open() it again would result in an exception. 再次尝试.Open()会导致异常。 I trust this is because I did not set "Pooling=False" in the connection string. 我相信这是因为我没有在连接字符串中设置“ Pooling = False”。 I'll experiment with it. 我会尝试一下。 If you have any thoughts on this one too, feel free to drop them here. 如果您对此也有任何想法,请随时将其放在此处。

So, in short, I'd like some opinions on how to organize my MySQLConnections. 简而言之,我想就如何组织MySQLConnections提出一些意见。 If you think a single static MySQLConnection to be used by all of the program's classes is better (not necessarily performance-wise, I'm talking more about the effect of multiple MySQLConnections on the database system itself), let me know why you think so. 如果您认为程序的所有类都使用单个静态MySQLConnection更好(不一定是性能方面的问题,我在谈论的是更多MySQLConnections对数据库系统本身的影响),请告诉我您为什么这么认为。

I'm expecting for the final program to have around 10 or 15 classes, each actively querying the database. 我期望最终程序具有大约10或15个类,每个类都在积极查询数据库。

My rules of thumb are: 我的经验法则是:

  • keep connections open for as brief a time as possible 保持连接打开尽可能短的时间
  • let ADO.NET handle connection pooling for you 让ADO.NET为您处理连接池
  • share connections only when the processes are particpating in a transaction together 仅当流程一起参与事务时才共享连接

So, no you should not use one global static connection. 因此,不,您不应该使用一个全局静态连接。 But you could have a utility method that supplies your data fetching methods with an open connection. 但是您可以使用一种实用程序方法,为您的数据获取方法提供开放的连接。 Then you would do something like (assuming Sql is your utility class): 然后,您将执行以下操作(假设Sql是您的实用程序类):

public IEnumerable<MyClass> GetSomeData()
{
    using (var cn = Sql.GetOpenConnection())
    {
        //get your data here
    }
}

Do not create a single shared connection. 不要创建单个共享连接。 Open as late as possible and close as early as possible. 尽早开放,尽早关闭。 If you need to use a connection for multiple queries, try looking at MARS (multiple active record sets) I don't know if MySQL connector supports that though. 如果您需要对多个查询使用连接,请尝试查看MARS(多个活动记录集),但我不知道MySQL连接器是否支持该连接。

certianly let the system handle connection pooling. 确实让系统处理连接池。 db connections are expensive. 数据库连接很昂贵。

You can continue with one connection per class. 您可以在每个班级继续一个连接。 Most ADO.NET providers use connection pooling per default as you have noticed. 您已经注意到,大多数ADO.NET提供程序默认都使用连接池。 Close doesn't really close the connection but return the connection to the pool. Close并不会真正关闭连接,而是将连接返回到池中。 However, you should not try to Open() the connection again but create a new connection object. 但是,您不应尝试再次Open()连接,而应创建一个新的连接对象。

There is one downfall with using one connection per class and that's transaction handling. 每类使用一个连接会导致一次失败,那就是事务处理。 Transactions can not be shared over multiple connections (unless you are using TransactionScope ). 不能通过多个连接共享事务(除非您正在使用TransactionScope )。

I usually prefer one connection per "session" and take in the connection in the constructor to my repository classes. 我通常更喜欢每个“会话”一个连接,并在构造函数中将其连接到我的存储库类。 (As I usually use inversion of control containers). (因为我通常使用控件容器的反转)。 Google a bit about Unit Of Work implementations. Google谈到了工作单元的实现。

public class DALCommon
{
    public static string GetConnectionString
    {
        //return System.Configuration.ConfigurationManager.AppSettings["connectionInfo"];

        get
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            string server = appSettings["server"];
            string userid = appSettings["userid"];
            string password = appSettings["password"];

            return String.Format("server={0};user id={1}; password={2}; database=dbmystock; pooling=false", server, userid, password);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM