当前位置:网站首页>Database connection under WinForm
Database connection under WinForm
2022-06-13 07:03:00 【AndroidOrCSharp】
BS Architecturally MVC The project can be used directly EntityFrameWork To establish a database connection , The connection information will be recorded in config In file , But for Winfrom project , You can set up your own database connection information
string dataBaseConnect="Data Source=244db;user=dc_ch;password=dc;Pooling = True;Max Pool Size = 1024;Min Pool Size = 4;";
When the type of execution is a stored procedure , The default is synchronous execution , For some time-consuming tasks , It can be set to execute asynchronously , Just declare in the connection AsynchronousProcessing = TRUE;
Before we begin, let's understand the concept of database connection pool
One . What is a database connection pool
Whenever the program needs to read and write to the database .Connection.Open() Will use ConnectionString Connect to database , The database will create for the program A connection , And keep it open , After that, the program can use T-SQL Statement to query / Update the database . When executed Connection.Close() after , The database will shut down when Front connection .
But in my actual operation , If frequently opened / Close the connection , It is undoubtedly a waste of resources ,ADO.Net Team A better solution is given . Put the previous Connection Save up , The next time you need to open the connection, the previous Connection Give it to the next connection . This is it. Connection Pool.
Two 、 database Connection Pool Connection pool Mode of operation
1、 When a program executes Connection.open() When ,ADO.net You need to judge , Whether this connection supports Connection Pool (Pooling The default is True)
(1)、 If specified as False, ADO.net Create a connection with the database , And then back to the program .
(2)、 If specified as True,ADO.net Will be based on ConnectString Create a Connection Pool, And then to Connection Pool Fill in Connection. Fill in how many Connection from Min Pool Size ( The default is 0) Attribute to determine . For example, if specified as 5, be ADO.net Once with SQL Open between databases 5 A connection , And then 4 individual Connection, Save in Connection Pool in ,1 individual Connection Back to the program .
2、 When the program is executed to Connection.close() When . If Pooling by True,ADO.net Just put the current Connection Put it in Connection Pool And maintain the connection with the database .
At the same time, it will judge Connection Lifetime( The default is 0) attribute ,0 For infinity , If Connection It has existed for more than Connection LifeTime,ADO.net It will close Connection At the same time, disconnect from the database , Instead of saving back to Connection Pool in .
3、 Next time Connection.Open() When it comes to execution ,ADO.Net Will judge the new ConnectionString As previously saved in Connection Pool Medium Connection Of connectionString Is it consistent .
4、 ADO.net Need to judge the current Connection Pool Is there anything that can be used in Connection( Not occupied by other programs ), If not ,ADO.net You need to judge ConnectionString set up Placed Max Pool Size ( The default is 100)
(1)、 If Connection Pool All in Connection Don't reach Max Pool Size,ADO.net Will connect to the database again , Create a connection , And then Connection Back to the program .
(2)、 If it's reached MaxPoolSize,ADO.net No new connections will be created again , But wait Connection Pool Occupied by other programs in Connection Release , This waiting time is affected by SqlConnection.ConnectionTimeout( The default is 15 second ) Limit , In other words, if the time exceeds 15 second ,SqlConnection Will throw a timeout error .
5、 If available Connection, from Connection Pool Take out Connection Nor is it directly returned to the program ,ADO.net We need to check ConnectionString Of ConnectionReset attribute ( The default is True) Is it necessary to Connection For the first time reset.
3、 ... and 、ASP.NET Program pair max pool size Configuration of
<add key="data" value="server=192.168.1.123; Port=3306; uid=root; pwd=root;database=data;pooling=true;min pool size=5;max pool size=512;connect timeout = 20; "/>
among Max Pool Size If it is not set, it defaults to 100, The theoretical maximum is 32767. The maximum number of connections is the maximum number of connections that the connection pool can request , If database connection requests exceed this number , Later database connection requests will be added to the waiting queue , This will affect subsequent database operations . In the waiting line , The default time to wait for a connection to the server is 15 second .
Four 、 View the number of application pools
select * from sysprocesses where dbid= db_id(' Database name ')
5、 ... and 、max pool size Configuration related Common mistakes
Exception details
System.InvalidOperationException: The timeout has expired . The timeout has expired , But the connection has not been obtained from the pool . This may be because all pool connections are in use , And reached the maximum pool size .
Problem description
We get the above exception when the connection exceeds the maximum value of the connection pool . Generally, the maximum connection pool is 100. When we get a connection that exceeds the maximum ,ADO.NET Timed out waiting for connection pool to return connection , This will throw the above exception
resolvent
1、 What we need to do is close the connection immediately after we use it
2、 Use data caching on pages that access the database , If the data on the page is not updated frequently ( Update every few minutes ) Words , Use Cache Objects can use the contents of the cache without accessing the database , Then the number of connections can be greatly reduced .
3、 Can be in WEB.config Inside, modify the... In the connection string Max Pool Size = N; To dynamically expand the maximum number of connections in the connection pool .
First declare a public connection method class , This class declares connection establishment methods and transaction related ( Turn on , Submit , Roll back )
public class TransController : IDisposable
{
#region Member variables
// Database type
DatabaseType _DatabaseType = DatabaseType.ORACLE;
/// <summary>
/// Database connection
/// </summary>
IDbConnection _cnn = null;
/// <summary>
/// Internal affairs
/// </summary>
IDbTransaction _trans = null;
/// <summary>
/// Inside Helper
/// </summary>
IHelper _helper = null;
/// <summary>
/// ADOHelper
/// </summary>
ADOHelper _ADOHelper = null;
/// <summary>
/// State of affairs
/// </summary>
TransState _state = TransState.NotInTrans;
/// <summary>
/// Whether the transaction starts flag
/// </summary>
bool _isTransfer = false;
/// <summary>
/// Transaction status enumeration
/// </summary>
enum TransState
{
InTrans = 0,
NotInTrans = 1
}
#endregion
#region Member attribute
/// <summary>
/// Business
/// </summary>
public IDbTransaction Trans
{
get { return _trans; }
}
/// <summary>
/// Helper
/// </summary>
public IHelper Helper
{
get { return _helper; }
}
/// <summary>
/// ADOHelper
/// </summary>
public ADOHelper ADOHelper
{
get { return _ADOHelper; }
}
/// <summary>
/// Whether to enable transactions
/// </summary>
public bool IsTransfer
{
get { return _isTransfer; }
}
/// <summary>
/// Connection database type
/// </summary>
public DatabaseType DatabaseType
{
get { return _DatabaseType; }
}
#endregion
#region Obsolete interface , Keep it down compatible
/// <summary>
/// Database type , Deprecated , Keep it down compatible
/// </summary>
public string dbTypeNew
{
get { return _DatabaseType.ToString(); }
}
#endregion
#region Structure and deconstruction
internal TransController(IHelper helper, ADOHelper adohelper, string cnnString)
{
_cnn = helper.CreateConnection(cnnString);
_cnn.Open();
_helper = helper;
_ADOHelper = adohelper;
_DatabaseType = helper.DatabaseType;
}
/// <summary>
/// Destructor , Release resources
/// </summary>
~TransController()
{
Dispose(false);
}
#endregion
#region Transaction control interface
/// <summary>
/// Start transaction
/// </summary>
public void BeginTransaction()
{
if (_isTransfer)
{
return;
}
if (_state == TransState.NotInTrans)
{
_trans = _cnn.BeginTransaction();
_state = TransState.InTrans;
}
}
/// <summary>
/// Commit transaction
/// </summary>
public void Commit()
{
if (_isTransfer)
{
return;
}
Debug.Assert(_state == TransState.InTrans && _trans != null);
if (_state == TransState.InTrans)
{
_trans.Commit();
_state = TransState.NotInTrans;
}
}
/// <summary>
/// Roll back the transaction
/// </summary>
public void Rollback()
{
if (_isTransfer)
{
return;
}
Debug.Assert(_state == TransState.InTrans && _trans != null);
if (_state == TransState.InTrans)
{
_trans.Rollback();
_state = TransState.NotInTrans;
}
}
/// <summary>
/// Start internal affairs
/// </summary>
public void StartTransfer()
{
Debug.Assert(_isTransfer == false && _state == TransState.InTrans && _trans != null);
_isTransfer = true;
}
/// <summary>
/// End internal transactions
/// </summary>
public void EndTransfer()
{
Debug.Assert(_isTransfer == true && _state == TransState.InTrans && _trans != null);
_isTransfer = false;
}
/// <summary>
/// close
/// </summary>
public void Close()
{
Dispose();
}
#endregion
#region IDisposable member
/// <summary>
/// Release occupied resources
/// </summary>
public void Dispose()
{
if (_isTransfer)
{
EndTransfer();
return;
}
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
_cnn = null;
}
#endregion
}Then use this class to establish a database connection in the actual process
string dataBaseType="ORACLE";
string dataBaseConnect="Data Source=244db;user=dc_ch;password=dc;Pooling = True;Max Pool Size = 1024;Min Pool Size = 4;";
TransController link = HelperFactory.CreateTransController(modual.DataBase.Type, modual.DataBase.Connect);
/// <summary>
/// Create a database operation object according to the specified database type
/// </summary>
/// <param name="type"> Database type </param>
/// <returns>Helper Interface </returns>
public static Helper CreateHelper(DatabaseType type)
{
switch (type)
{
case DatabaseType.SQLSERVER:
{
return new SqlHelper();
}
case DatabaseType.ORACLE:
{
return new OracleHelper();
}
default:
{
throw new Exception(DONT_SUPPORT);
}
}
}
#region Create a transaction controller
/// <summary>
/// Create a transaction controller
/// </summary>
/// <param name="dbType"> Database type </param>
/// <param name="cnnString"> Connection string </param>
/// <returns> Transaction controller </returns>
public static TransController CreateTransController(DatabaseType dbType, string cnnString)
{
Helper helper = CreateHelper(dbType);
return new TransController(helper, new ADOHelper(helper), cnnString);
}
such , This link We can use it directly . for instance
// Cache function parameters
try
{
if (this.link != null)
{
log.Info(" Load interface cache data .");
FuncCache.Modual = modual.ModualCode;
this.link.BeginTransaction();
DataSet item = this.link.Helper.ExecuteDataset(this.link.Trans, CommandType.Text, "SELECT * FROM SYS_FUNCTIONINFO WHERE FUNCTIONSTATE = 'N' ORDER BY FUNCTIONCODE");
if (item != null || item.Tables[0].Rows.Count > 0)
{
FuncCache.FuncInfo = item.Tables[0];
}
item = this.link.Helper.ExecuteDataset(this.link.Trans, CommandType.Text, "SELECT T.* FROM SYS_FUNCTIONDETAIL T,SYS_FUNCTIONINFO F WHERE T.FUNCTIONCODE = F.FUNCTIONCODE AND F.FUNCTIONSTATE = 'N' ORDER BY T.FUNCTIONCODE,T.POSITION");
if (item != null || item.Tables[0].Rows.Count > 0)
{
FuncCache.FuncParam = item.Tables[0];
}
this.link.Commit();
}
}
catch (Exception ex)
{
this.link.Rollback();
RetMsg = ex.Message;
throw new Exception(" Get function interface " + ex.Message);
}
// among CommandType Indicate that the execution is SQL Or stored procedure
public enum CommandType
{
Text = 1,
StoredProcedure = 4,
TableDirect = 512
}Here is the winform How to manage database connection related knowledge .
边栏推荐
- Jinglianwen technology provides a one-stop smart home data acquisition and labeling solution
- 1154. 一年中的第几天
- 同花顺可以开股票账户吗?安全吗?
- 简单了解C语言基本语
- Monotone stack top31 of interview must brush algorithm top101
- 数字时代进化论
- [cloud native | kubernetes] kubernetes configuration
- Br backup test
- 玄武云科技通过上市聆讯:业绩波动明显,陈永辉等三人为控股股东
- 上位机开发(固件下载软件之软件测试)
猜你喜欢

Project analysis of Taishan crowdfunding mode: why is Taishan crowdfunding mode so popular?

SDN basic overview

First day of learning MySQL Basics

That is, after the negative impact of gcat advertising e-commerce, is there no stable advertising e-commerce platform?

Nfv basic overview

Tikv key performance parameters and optimization
![[weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background](/img/11/d6cd333a2fa56af2dc61b7597f1ada.png)
[weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background

Tidb statistics

数字时代进化论

Upper computer development (detailed design of firmware download software)
随机推荐
RT thread simulator lvgl control: switch switch button control
June 12, 2022: if there are n*n pieces in an n*n square chessboard, each grid can have exactly one piece. But now some pieces are gathered on a grid, such as 2030100300. The above two-dimensional arra
RT-Thread 模拟器 simulator LVGL控件:switch 开关按钮控件
Learning notes of MySQL series by database and table
景联文科技提供语音数据采集标注服务
Normalizing y-axis in histograms in R ggplot to proportion
Jinglianwen technology provides voice data acquisition and labeling services
[Tencent Alibaba's most comprehensive collection of test questions] (four sides: three rounds of technology +1 round of HR)
json. Stringify() and json The difference between parse () and json Usage of stringify()
Jinglianwen Technology: current situation and solutions of data annotation industry
[weak transient signal detection] matlab simulation of SVM detection method for weak transient signal under chaotic background
NFV基本概述
Intelligent entertainment has developed steadily, and jinglianwen technology provides data collection and labeling services
上位机开发(固件下载软件之详细设计)
JS method of extracting numbers from strings
景联文科技提供一站式智能家居数据采集标注解决方案
1154. day of the year
百货中心供应链管理系统
【云原生 | Kubernetes篇】Kubernetes 配置
Tidb implementation plan -- I