83 lines
2.5 KiB
C#
83 lines
2.5 KiB
C#
using MySql.Data.MySqlClient;
|
|
using System;
|
|
using System.Configuration;
|
|
|
|
namespace 全自动水压检测仪.DATA
|
|
{
|
|
internal static class DatabaseConnectionManager
|
|
{
|
|
private const string ConnectionStringName = "FullAutoWaterPressure";
|
|
private const string DefaultConnectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;";
|
|
|
|
private static readonly Lazy<string> _connectionString = new Lazy<string>(BuildConnectionString);
|
|
|
|
public static string ConnectionString => _connectionString.Value;
|
|
|
|
public static MySqlConnection CreateConnection()
|
|
{
|
|
return new MySqlConnection(ConnectionString);
|
|
}
|
|
|
|
private static string BuildConnectionString()
|
|
{
|
|
string configuredConnectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName]?.ConnectionString;
|
|
string rawConnectionString = string.IsNullOrWhiteSpace(configuredConnectionString)
|
|
? DefaultConnectionString
|
|
: configuredConnectionString;
|
|
|
|
try
|
|
{
|
|
var builder = new MySqlConnectionStringBuilder(rawConnectionString);
|
|
|
|
if (string.IsNullOrWhiteSpace(builder.Server))
|
|
{
|
|
builder.Server = "localhost";
|
|
}
|
|
|
|
if (builder.Port == 0)
|
|
{
|
|
builder.Port = 3306;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(builder.Database))
|
|
{
|
|
builder.Database = "fullautowaterpressure";
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(builder.UserID))
|
|
{
|
|
builder.UserID = "root";
|
|
}
|
|
|
|
if (builder.ConnectionTimeout == 0)
|
|
{
|
|
builder.ConnectionTimeout = 5;
|
|
}
|
|
|
|
if (builder.DefaultCommandTimeout == 0)
|
|
{
|
|
builder.DefaultCommandTimeout = 30;
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(builder.CharacterSet))
|
|
{
|
|
builder.CharacterSet = "utf8";
|
|
}
|
|
|
|
builder.Pooling = true;
|
|
|
|
if (builder.MaximumPoolSize == 0)
|
|
{
|
|
builder.MaximumPoolSize = 50;
|
|
}
|
|
|
|
return builder.ConnectionString;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return DefaultConnectionString;
|
|
}
|
|
}
|
|
}
|
|
}
|