using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OA { class MySQLHelper { /// <summary> /// 数据库位置. 本机为句点或是localhost. 远程服务器为IP地址或域名. 如果不是默认端口,则使用逗号分隔加在地址后面. /// </summary> public static string DataSource { get; set; } = "localhost"; /// <summary> /// 要连接的目标数据库 /// </summary> public static string DatabaseName { get; set; } = "oa"; /// <summary> /// 连接数据库时使用的账号 /// </summary> public static string DbUser { get; set; } = "oa"; /// <summary> /// 连接数据库时使用的密码 /// </summary> public static string DbPassword { get; set; } = "abcd1234"; /// <summary> /// 连接串 /// </summary> public static string ConnectionString { get { // return "Data Source=127.0.0.1;Database='oa';User id = 'root'; Password='';Charset='utf8';Allow Zero Datetime=True"; return $"server={DataSource};port=3306;user={DbUser};password={DbPassword}; database={DatabaseName};Pooling=false;Charset='utf8';Allow Zero Datetime=True"; } } private static MySqlConnection m_DbConnection = null; /// <summary> /// 打开数据库. /// </summary> public static void Open() { try { if (m_DbConnection == null) m_DbConnection = new MySqlConnection(ConnectionString); if (m_DbConnection.State == System.Data.ConnectionState.Closed) m_DbConnection.Open(); } catch { throw new Exception("数据库连接失败,请确定是否打开。"); } } /// <summary> /// 关闭数据库. /// </summary> public static void Close() { if (m_DbConnection == null) return; if (m_DbConnection.State != System.Data.ConnectionState.Closed) m_DbConnection.Close(); } /// <summary> /// 执行查询 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static int ExecuteNonQuery(string sql) { Close(); Open(); MySqlCommand dbCommand = new MySqlCommand(sql, m_DbConnection); int ret = dbCommand.ExecuteNonQuery(); //dbCommand.Dispose(); //Close(); return ret; } /// <summary> /// 执行查询并返回结果集 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static MySqlDataReader ExecuteReader(string sql) { Close(); Open(); MySqlCommand oleDbCommand = new MySqlCommand(sql, m_DbConnection); //return oleDbCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection); return oleDbCommand.ExecuteReader(); } public static object ExecuteScalar(string sql) { Close(); Open(); MySqlCommand dbCommand = new MySqlCommand(sql, m_DbConnection); object result = dbCommand.ExecuteScalar(); //dbCommand.Dispose(); //Close(); return result; } } }
标签:帮助,return,string,DbConnection,数据库,System,static,mysql,public From: https://www.cnblogs.com/cxyyn/p/17777462.html