本文介绍了如何用C#语言实现数据库连接的单例设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 大家好, i有winform c#visual studio 2012 i想要实现单身设计模式 其实我不知道我想在每次需要请求数据库时打开一个新的连接。 在进入数据库之前,我想检查连接是否已经打开 if它打开,所以不需要创建一个新实例 否则,创建。 在我的应用程序的每个页面中,我只想在需要数据时调用我的单例数据库无需打开或关闭数据库连接 我尝试过:Hi everybody,i have winform c# visual studio 2012i want to implement "singleton design pattern"in fact i don't want to open a new connection every time i need to request the database.before going to the database, i want to check if the connection is already open or notif it opens, so no need to create a new instanceotherwise, create.And in every page of my app i just want to call my singleton whenever i need data from database without having to open or close again a DB connectionWhat I have tried:namespace GNMS{ public class Godaddy { //singleton has a reference to itself private static Godaddy dbconec; private Godaddy() { }//private constructor so that it cannot be instantiated outside this class //grabs instance of singleton pattern public static Godaddy GetInstance() { if (dbconec == null) //check if an instance has been created else can create a new instance { dbconec = new Godaddy(); } return dbconec; } public string connectDB() //Database connection { try { //create a string connection string strconnection; strconnection = "Server=x.x.x.x; Database =xxx; Uid = xxx; Password =xxx;CharSet=utf8; Connect Timeout=60;"; //initialize the connection to DB MySqlConnection conn = new MySqlConnection(strconnection); conn.Open(); return strconnection; //conn.Close(); } catch (Exception ex) { return ex.Message; } } //// }}推荐答案 这篇关于如何用C#语言实现数据库连接的单例设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-03 08:15