码迷,mamicode.com
首页 > 数据库 > 详细

MYSQL 常用类

时间:2020-07-15 15:44:37      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:stat   ldb   serve   system   cat   返回值   enc   ++   returns   

1.生成创建数据库

using MySql.Data.MySqlClient;
using System;
using System.Data;
using Utility;

namespace OFZ.DBLib
{
public class MySqlDBHelper
{
#region Instance
private static MySqlDBHelper m_Instance;
public static MySqlDBHelper Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new MySqlDBHelper();
}
return m_Instance;
}
}
#endregion Instance

#region Fields
private string _ServerIP = string.Empty;
private string _DBName = string.Empty;
private uint _DBPort = 0;
private string _UserName = string.Empty;
private string _UserPassword = string.Empty;
private string _ConnectionStringWithoutDB = string.Empty;
public string _ConnectionStringWithDB = string.Empty;
#endregion Fields

public bool CreateDB(string ServerIP, string dbName, uint dbPort, string userName, string userPassword, ref string errorInfo)
{
_ServerIP = ServerIP; _DBName = dbName; _DBPort = dbPort; _UserName = userName; _UserPassword = userPassword;

string strTemp = @"SERVER={0};Port={1};UID={2};PASSWORD={3};Charset=utf8;";
_ConnectionStringWithoutDB = string.Format(strTemp, ServerIP, dbPort, userName, userPassword);
strTemp = @"SERVER={0};Port={1};DATABASE={2};UID={3};PASSWORD={4};Charset=utf8;";
_ConnectionStringWithDB = string.Format(strTemp, ServerIP, dbPort, dbName, userName, userPassword);

if (!CreateDatabase())
{
errorInfo = string.Format("数据库:{0} 创建失败!", _DBName);
return false;
}

MySqlManager.Instance.Init(_ConnectionStringWithDB);

if (!CreateAlarmsTable())
{
errorInfo = "数据库表:Alarms 创建失败!";
return false;
}

if (!CreatePermissions())
{
errorInfo = "数据库表:Permissions 创建失败!";
return false;
}

if (!CreateGroups())
{
errorInfo = "数据库表:Groups 创建失败!";
return false;
}

if (!CreateUsersTable())
{
errorInfo = "数据库表:Users 创建失败!";
return false;
}

if (!CreateLogTable())
{
errorInfo = "数据库表:Log 创建失败!";
return false;
}

if(!CreatePRTable())
{
errorInfo = "数据库表:PR 创建失败!";
return false;
}

if (!CreatePRBackupTable())
{
errorInfo = "数据库表:PRBackup 创建失败!";
return false;
}

if (!CreatePRSourceTable())
{
errorInfo = "数据库表:PRSourceData 创建失败!";
return false;
}

if (!CreateDebugLogTable())
{
errorInfo = "数据库表:DebugLogTable 创建失败!";
return false;
}
return true;
}

/// <summary>
/// 创建数据库
/// </summary>
/// <returns></returns>
private bool CreateDatabase()
{
MySqlManager.Instance.Init(_ConnectionStringWithoutDB);
string sql = string.Format(@"CREATE DATABASE IF NOT EXISTS `{0}` /*!40100 DEFAULT CHARACTER SET gb2312 */", _DBName);
try
{
var rslt = MySqlManager.Instance.Execute(sql);
return (rslt >= 0);
}
catch (Exception ex)
{
LogHelper.LogError("CreateDatabase : " + ex.Message);
return false;
}
}

/// <summary>
/// 创建警报数据库表
/// </summary>
/// <returns></returns>
private bool CreateAlarmsTable()
{
string sql = "CREATE TABLE if not exists alarms (AlarmId VARCHAR(17) PRIMARY KEY NOT NULL, ";
sql += "AlarmTime DATETIME NOT NULL, ProjectId TEXT NOT NULL, ProjectName TEXT, ";
sql += "DefenceId TEXT NOT NULL, DefenceName TEXT, PRCode INT, Processed BOOL, Operator TEXT,";
sql += "Note TEXT, waveDataPath TEXT, AlarmEndTime DATETIME, AlarmType INT NOT NULL,DenfenceType INT NOT NULL, PortNum INT NOT NULL);";
try
{
int rslt = MySqlManager.Instance.Execute(sql);

if (rslt < 0)
{
return false;
}
return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreateUsersTable" + ex.Message);
}
return false;
}

/// <summary>
/// PermissionId默认值:0.超级管理员;1.管理员;2.操作员
/// </summary>
/// <returns></returns>
private bool CreatePermissions()
{
string sql = "CREATE TABLE if not exists Permissions (";
sql += "PermissionId INT PRIMARY KEY NOT NULL,";
sql += "Settings BOOL NOT NULL,";
sql += "WaveView BOOL NOT NULL,";
sql += "Waterfall BOOL NOT NULL,";
sql += "DasSettings BOOL NOT NULL,";
sql += "Selflearning BOOL NOT NULL,";
sql += "PRManage BOOL NOT NULL,";
sql += "LogView BOOL NOT NULL,";
sql += "UserManage BOOL NOT NULL,";
sql += "EventCenter BOOL NOT NULL,";
sql += "CameraManage BOOL NOT NULL,";
sql += "DeviceAdd BOOL NOT NULL,";
sql += "DeviceModify BOOL NOT NULL,";
sql += "DeviceDel BOOL NOT NULL,";
sql += "AllArming BOOL NOT NULL,";
sql += "AllDisarming BOOL NOT NULL,";
sql += "TimeDisarming BOOL NOT NULL,";
sql += "LinkageSettings BOOL NOT NULL);";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

sql = "Select * from Permissions;";
DataTable dt = MySqlManager.Instance.Query(sql);
if (dt == null || 0 == dt.Rows.Count)
{
sql = "Insert into Permissions(PermissionId,Settings,WaveView,Waterfall,DasSettings,Selflearning," +
"PRManage,LogView,UserManage,EventCenter,CameraManage,DeviceAdd,DeviceModify,DeviceDel,AllArming,AllDisarming,TimeDisarming,LinkageSettings)" +
"values (‘0‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘, ‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘)," +
"(‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘0‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘,‘1‘)," +
"(‘2‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘0‘,‘1‘,‘1‘,‘1‘,‘0‘)";
if (MySqlManager.Instance.Execute(sql) <= 0) return false;
}
return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreateUsersTable" + ex.Message);
}
return false;
}

/// <summary>
/// 创建用户权限表
/// </summary>
/// <returns></returns>
/// (
private bool CreateGroups()
{
string sql = "CREATE TABLE if not exists groups (";
sql += "GroupId INT PRIMARY KEY NOT NULL,";
sql += "GroupName VARCHAR(45) NOT NULL,";
sql += "PermissionId INT NOT NULL,constraint `gfk` foreign key (`PermissionId`) references `Permissions`(`PermissionId`));";
try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

sql = "Select * from groups;";
DataTable dt = MySqlManager.Instance.Query(sql);
if (dt == null || 0 == dt.Rows.Count)
{
sql = "Insert into groups(GroupId,GroupName,PermissionId)" +
"values (‘0‘,‘SuperAdmin‘,‘0‘)," +
"(‘1‘,‘Admin‘,‘1‘)," +
"(‘2‘,‘operator‘,‘2‘)";

if (MySqlManager.Instance.Execute(sql) <= 0) return false;
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
LogHelper.LogError("CreateUsersTable" + ex.Message);
}
return false;
}

/// <summary>
/// 创建用户表
/// </summary>
/// <returns></returns>
private bool CreateUsersTable()
{
string sql = "CREATE TABLE if not exists users (";
sql += "UserId VARCHAR(45) PRIMARY KEY NOT NULL,";
sql += "Name VARCHAR(45) NOT NULL,";
sql += "Password VARCHAR(45) NOT NULL,";
sql += "GroupId INT NOT NULL ,constraint `ufk` foreign key (`GroupId`) references `groups`(`GroupId`));";
try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

sql = "Select * from users;";
DataTable dt = MySqlManager.Instance.Query(sql);
if (dt == null || 0 == dt.Rows.Count)
{
sql = "Insert into users (UserId,Name,Password,GroupId) Values(‘ksgz001‘,‘Maintainer‘,‘FlPMSLj/XGPXVVYDeDRtjQ==‘,‘0‘),(‘ksgz002‘,‘Admin‘,‘GKFZy3ZETQ8=‘,‘1‘),(‘ksgz003‘,‘operator‘,‘XyQUovF++8c=‘,‘2‘);";
if (MySqlManager.Instance.Execute(sql) <= 0) return false;
}
return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreateUsersTable" + ex.Message);
}
return false;
}

/// <summary>
/// 创建日志数据库表
/// </summary>
/// <returns></returns>
private bool CreateLogTable()
{
string sql = "CREATE TABLE if not exists log(";
sql += "LogId VARCHAR(17) PRIMARY KEY NOT NULL,";
sql += "LogType int(11) NOT NULL,";
sql += "UserName varchar(45) DEFAULT NULL,";
sql += "UserGroup int(11) DEFAULT NULL,";
sql += "UserGroupName varchar(45) DEFAULT NULL,";
sql += "LogTime DATETIME NOT NULL,";
sql += "Info TEXT NOT NULL);";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreateLogTable" + ex.Message);
}
return false;
}

private bool CreatePRTable()
{
string sql = "CREATE TABLE if not exists `pr`(";
sql += "`pr_ID` varchar(45) NOT NULL,";
sql += "`pr_Type` int(11) NOT NULL,";
sql += "`pr_Name` varchar(45) NOT NULL,";
sql += "`pr_Time` datetime NOT NULL,";
sql += "`pr_Datas` text NOT NULL,";
sql += "PRIMARY KEY (`pr_ID`)) ENGINE=InnoDB DEFAULT CHARSET=gb2312;";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreatePRTable:" + ex.Message);
}
return false;
}

private bool CreatePRBackupTable()
{
string sql = "CREATE TABLE if not exists `prbackup`(";
sql += "`pr_ID` varchar(45) NOT NULL,";
sql += "`pr_Type` int(11) NOT NULL,";
sql += "`pr_Name` varchar(45) NOT NULL,";
sql += "`pr_Time` datetime NOT NULL,";
sql += "`pr_Datas` text NOT NULL,";
sql += "PRIMARY KEY (`pr_ID`)) ENGINE=InnoDB DEFAULT CHARSET=gb2312;";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreatePRBackupTable:" + ex.Message);
}
return false;
}

private bool CreatePRSourceTable()
{
string sql = "CREATE TABLE if not exists `prsource`(";
sql += "`pr_ID` varchar(45) NOT NULL,";
sql += "`pr_Type` int(11) NOT NULL,";
sql += "`pr_Name` varchar(45) NOT NULL,";
sql += "`pr_Time` datetime NOT NULL,";
sql += "`pr_Datas` text NOT NULL,";
sql += "PRIMARY KEY (`pr_ID`)) ENGINE=InnoDB DEFAULT CHARSET=gb2312;";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreatePRSourceDataTable:" + ex.Message);
}
return false;
}

private bool CreateDebugLogTable()
{
string sql = "CREATE TABLE if not exists Debuglog(";
sql += "LogId int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,";
sql += "DeviceType varchar(20) NOT NULL,";
sql += "DeviceId varchar(45) NOT NULL,";
sql += "LogTime DATETIME NOT NULL,";
sql += "Info TEXT NOT NULL);";

try
{
int rslt = MySqlManager.Instance.Execute(sql);
if (rslt < 0) return false;

return true;
}
catch (Exception ex)
{
LogHelper.LogError("CreateLogTable" + ex.Message);
}
return false;
}

}
}

2.执行类

using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Globalization;
using Utility;

namespace OFZ.DBLib
{
public class MySqlManager
{
#region Fields
private MySqlConnection connection;
#endregion

#region Instance
private static MySqlManager m_Instance;
public static MySqlManager Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new MySqlManager();
}
return m_Instance;
}
}
#endregion

#region Public
/// <summary>
/// 初始化数据库
/// </summary>
/// <param name="connStr"></param>
public void Init(string connStr)
{
connection = new MySqlConnection(connStr);

}

/// <summary>
/// 打开数据库连接
/// </summary>
/// <returns></returns>
public bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
//WPFMessageBox.ShowError("Cannot connect to server. Contact administrator");
//LogHelper.LogError("OpenConnection : Cannot connect to server. Contact administrator");
break;
case 1045:
//WPFMessageBox.ShowError("Invalid username/password, please try again");
//LogHelper.LogError("OpenConnection : Invalid username/password, please try again");
break;
default:
//WPFMessageBox.ShowError(ex.Message);
//LogHelper.LogError("OpenConnection : " + ex.Message);
break;
}
return false;
}
}

/// <summary>
/// 关闭数据库连接
/// </summary>
/// <returns></returns>
public bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
//WPFMessageBox.ShowError(ex.Message);
//LogHelper.LogError("CloseConnection : " + ex.Message);
return false;
}
}

/// <summary>
/// 执行成功时返回值为该命令所影响的行数,如果影响的行数为0时返回的值为0,如果数据操作回滚得话返回值为-1
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public int Execute(string strSql)
{
try
{
if (!OpenConnection()) return -1;

var cmd = new MySqlCommand(strSql, connection);
return cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
throw new Exception(ex.Number.ToString(CultureInfo.InvariantCulture));
}
finally
{
if (connection.State != ConnectionState.Closed)
CloseConnection();
}
}

/// <summary>
/// 查询返回DataTable
/// </summary>
/// <param name="strSql"></param>
/// <returns></returns>
public DataTable Query(string strSql)
{
DataTable dt = null;

try
{
if (OpenConnection())
{
var ad = new MySqlDataAdapter(strSql, connection);
dt = new DataTable();
ad.Fill(dt);
}
return dt;
}
catch (MySqlException ex)
{
LogHelper.LogError("查询失败:"+ex.ToString());
return null;
}
finally
{
if (connection.State != ConnectionState.Closed)
CloseConnection();
}
}
#endregion
}
}

MYSQL 常用类

标签:stat   ldb   serve   system   cat   返回值   enc   ++   returns   

原文地址:https://www.cnblogs.com/gkxg/p/13305067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!