Advertisement
Guest User

Untitled

a guest
May 8th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.65 KB | None | 0 0
  1. using System;
  2. using System.Data.Odbc;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.IO;
  8. using System.Net;
  9.  
  10. using Server;
  11.  
  12. namespace Server.Vorspire.MySQL
  13. {
  14.     public partial class Config
  15.     {
  16.         public static bool
  17.             /// <summary>
  18.             /// Extended Errors
  19.             /// If this system, or any components of, throw any exceptions, they will be displayed in the Console window.
  20.             /// </summary> 
  21.             ExtendedErrors = false;
  22.  
  23.         public const string
  24.             SystemName = "MySQL";
  25.     }
  26.  
  27.     /// <summary>
  28.     /// ODBC Driver Versions
  29.     /// </summary>
  30.     public enum ODBCDriver
  31.     {
  32.         /// <summary>
  33.         /// Version 3.51
  34.         /// </summary>
  35.         _3_51 = 0x00000000,
  36.         /// <summary>
  37.         /// Version 5.1
  38.         /// </summary>
  39.         _5_1 = 0x00000001,
  40.     }
  41.  
  42.     /// <summary>
  43.     /// Provides a MySQL Result structure for storing MySQL query get-data.
  44.     /// </summary>
  45.     public struct MySQLResult
  46.     {
  47.         private int _ROW;
  48.         /// <summary>
  49.         /// Row ID of this result
  50.         /// </summary>
  51.         public int Row { get { return _ROW; } }
  52.  
  53.         private string _KEY;
  54.         /// <summary>
  55.         /// Row Column/Field Name of this result
  56.         /// </summary>
  57.         public string Key { get { return _KEY; } }
  58.  
  59.         private object _VAL;
  60.         /// <summary>
  61.         /// Value of this result
  62.         /// </summary>
  63.         public object Value { get { return _VAL; } }
  64.  
  65.         /// <summary>
  66.         /// Creates a MySQLResult structure object
  67.         /// </summary>
  68.         /// <param name="rowID">Row ID of this result</param>
  69.         /// <param name="key">Row Column/Field Name of this result</param>
  70.         /// <param name="value">Value of this result</param>
  71.         public MySQLResult(int rowID, string key, object value)
  72.         {
  73.             _ROW = rowID;
  74.             _KEY = key;
  75.             _VAL = value;
  76.         }
  77.  
  78.         public override string ToString()
  79.         {
  80.             return String.Format("[{0}][{1}] => '{2}'", _ROW, _KEY, _VAL);
  81.         }
  82.     }
  83.  
  84.     /// <summary>
  85.     /// Provides a MySQL Data structure for storing MySQL query put-data.
  86.     /// </summary>
  87.     public struct MySQLData
  88.     {
  89.         private string _KEY;
  90.         /// <summary>
  91.         /// Row Column/Field Name of this result
  92.         /// </summary>
  93.         public string Key { get { return _KEY; } }
  94.  
  95.         private string _VAL;
  96.         /// <summary>
  97.         /// Value of this result
  98.         /// </summary>
  99.         public string Value { get { return _VAL; } }
  100.  
  101.         /// <summary>
  102.         /// Creates a MySQLData structure object
  103.         /// </summary>
  104.         /// <param name="key">Column/Field Name of this data</param>
  105.         /// <param name="value">Value of this data</param>
  106.         public MySQLData(string key, string value)
  107.         {
  108.             _KEY = key;
  109.             _VAL = value;
  110.         }
  111.  
  112.         public override string ToString()
  113.         {
  114.             return String.Format("[{0}] => '{1}'", _KEY, _VAL);
  115.         }
  116.     }
  117.  
  118.     /// <summary>
  119.     /// Provides a basic MySQL Connection Class that wraps the OdbcConnection class.
  120.     /// </summary>
  121.     public class MySQLConnection
  122.     {
  123.         private string _IP;
  124.         /// <summary>
  125.         /// MySQL Server IP Address
  126.         /// </summary>
  127.         public string IP { get { return _IP; } }
  128.  
  129.         private string _USER;
  130.         /// <summary>
  131.         /// MySQL Access User Name
  132.         /// </summary>
  133.         public string User { get { return _USER; } }
  134.  
  135.         private string _PASS;
  136.         /// <summary>
  137.         /// MySQL Access Password
  138.         /// </summary>
  139.         public string Password { get { return _PASS; } }
  140.  
  141.         private string _DBNAME;
  142.         /// <summary>
  143.         /// MySQL Database Name
  144.         /// </summary>
  145.         public string DBName { get { return _DBNAME; } }
  146.  
  147.         private string _MESSAGE;
  148.         /// <summary>
  149.         /// OdbcConnection extension: Message
  150.         /// </summary>
  151.         public string Message { get { return _MESSAGE; } }
  152.  
  153.         private OdbcError[] _ERRORS;
  154.         /// <summary>
  155.         /// OdbcConnection extension: Errors
  156.         /// </summary>
  157.         public OdbcError[] Errors { get { return _ERRORS; } }
  158.  
  159.         private ODBCDriver _DRIVER;
  160.         /// <summary>
  161.         /// OdbcConnection Driver Version
  162.         /// </summary>
  163.         public ODBCDriver Driver { get { return _DRIVER; } }
  164.  
  165.         private OdbcConnection _CONNECTION;
  166.         /// <summary>
  167.         /// OdbcConnection Instance
  168.         /// </summary>
  169.         public OdbcConnection Connection { get { return _CONNECTION; } }
  170.  
  171.         /// <summary>
  172.         /// Returns true if the Connection is Open
  173.         /// </summary>
  174.         public bool Connected { get { return (_CONNECTION != null && _CONNECTION.State == System.Data.ConnectionState.Open); } }
  175.  
  176.         /// <summary>
  177.         /// Returns true if the Connection contains Errors
  178.         /// </summary>
  179.         public bool HasError { get { return (_ERRORS != null && _ERRORS.Length > 0); } }
  180.  
  181.         /// <summary>
  182.         /// Creates a MySQL Connection object
  183.         /// </summary>
  184.         /// <param name="ip">MySQL Server IP Address</param>
  185.         /// <param name="user">MySQL Access User Name</param>
  186.         /// <param name="pass">MySQL Access Password</param>
  187.         /// <param name="dbName">MySQL Database Name</param>
  188.         /// <param name="driver">OdbcConnection Driver Version</param>
  189.         public MySQLConnection(string ip, string user, string pass, string dbName, ODBCDriver driver)
  190.         {
  191.             _IP = ip;
  192.             _USER = user;
  193.             _PASS = pass;
  194.             _DBNAME = dbName;
  195.             _DRIVER = driver;
  196.         }
  197.  
  198.         /// <summary>
  199.         /// Called when the Connection instance receives any messages.
  200.         /// Resets the MySQLConnection object Message and Errors members.
  201.         /// </summary>
  202.         /// <param name="sender">Sender object</param>
  203.         /// <param name="e">Odbc Message Event Arguments</param>
  204.         private void OnMessage(object sender, OdbcInfoMessageEventArgs e)
  205.         {
  206.             if (e.Errors != null && e.Errors.Count > 0)
  207.             {
  208.                 OdbcErrorCollection errList = e.Errors;
  209.  
  210.                 _ERRORS = new OdbcError[errList.Count];
  211.  
  212.                 for (int i = 0; i < errList.Count; i++)
  213.                 {
  214.                     _ERRORS[i] = errList[i];
  215.                 }
  216.             }
  217.             else
  218.             {
  219.                 _ERRORS = null;
  220.             }
  221.  
  222.             if (e.Message != null && e.Message.Length > 0)
  223.             {
  224.                 _MESSAGE = e.Message;
  225.             }
  226.             else
  227.             {
  228.                 _MESSAGE = null;
  229.             }
  230.         }
  231.  
  232.         /// <summary>
  233.         /// Attempts to connect to the specified MySQL Server with the given settings.
  234.         /// </summary>
  235.         /// <param name="retries">Retry connection attempts this many times if the initial connection fails.</param>
  236.         /// <returns>True if connection successful</returns>
  237.         public bool Connect(int retries)
  238.         {
  239.             string tmp = _DRIVER.ToString();
  240.  
  241.             tmp = tmp.Remove(0, 1);
  242.             tmp = tmp.Replace('_', '.');
  243.  
  244.             string driver = "{" + String.Format("MySQL ODBC {0} Driver", tmp) + "}";
  245.  
  246.             string con = String.Format("DRIVER={0};SERVER={1};DATABASE={2};UID={3};PASSWORD={4};", driver, _IP, _DBNAME, _USER, _PASS);
  247.  
  248.             try
  249.             {
  250.                 if (_CONNECTION == null)
  251.                 {
  252.                     _CONNECTION = new OdbcConnection(con);
  253.                     _CONNECTION.InfoMessage += new OdbcInfoMessageEventHandler(OnMessage);
  254.                     _CONNECTION.Open();
  255.  
  256.                     Console.WriteLine("[" + Config.SystemName + "] Connection Attempt.");
  257.                     while (_CONNECTION.State == System.Data.ConnectionState.Connecting)
  258.                     { }
  259.  
  260.                     if (_CONNECTION.State == System.Data.ConnectionState.Broken)
  261.                         _CONNECTION.Close();
  262.  
  263.                     if (_CONNECTION.State == System.Data.ConnectionState.Open)
  264.                     {
  265.                         Console.WriteLine("[" + Config.SystemName + "] Connection Successful.");
  266.                         return true;
  267.                     }
  268.                 }
  269.  
  270.                 if (_CONNECTION.State == System.Data.ConnectionState.Broken)
  271.                     _CONNECTION.Close();
  272.  
  273.                 if (_CONNECTION.State == System.Data.ConnectionState.Closed)
  274.                 {
  275.                     for (int i = 0; i < retries; i++)
  276.                     {
  277.                         _CONNECTION.Open();
  278.  
  279.                         Console.WriteLine("[" + Config.SystemName + "] Connection Attempt {0}.", i + 1);
  280.                         while (_CONNECTION.State == System.Data.ConnectionState.Connecting)
  281.                         { }
  282.  
  283.                         if (_CONNECTION.State == System.Data.ConnectionState.Broken)
  284.                             _CONNECTION.Close();
  285.  
  286.                         if (_CONNECTION.State == System.Data.ConnectionState.Open)
  287.                         {
  288.                             Console.WriteLine("[" + Config.SystemName + "] Connection Successful.");
  289.                             return true;
  290.                         }
  291.                     }
  292.                 }
  293.  
  294.                 if (_CONNECTION.State == System.Data.ConnectionState.Broken)
  295.                     _CONNECTION.Close();
  296.             }
  297.             catch (Exception ex)
  298.             {
  299.                 Console.WriteLine("[" + Config.SystemName + "] Connection Failed.");
  300.  
  301.                 if (Config.ExtendedErrors)
  302.                     Console.WriteLine("[" + Config.SystemName + "] {0}", ex);
  303.             }
  304.  
  305.             Console.WriteLine("[" + Config.SystemName + "] Connection Failed.");
  306.             Close();
  307.             return false;
  308.         }
  309.  
  310.         /// <summary>
  311.         /// Switches to a different Database Name on the connected MySQL Server
  312.         /// </summary>
  313.         /// <param name="dbName">Database Name to switch to</param>
  314.         /// <returns>True if switch successful</returns>
  315.         public bool SwitchDatabase(string dbName)
  316.         {
  317.             if (!Connected)
  318.             {
  319.                 _DBNAME = dbName;
  320.                 return true;
  321.             }
  322.  
  323.             _DBNAME = dbName;
  324.  
  325.             string query = String.Format("USE `{0}`", _DBNAME);
  326.  
  327.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  328.             cmd.CommandText = query;
  329.  
  330.             bool ret = (cmd.ExecuteNonQuery() > 0);
  331.  
  332.             cmd.Dispose();
  333.  
  334.             return ret;
  335.         }
  336.  
  337.         /// <summary>
  338.         /// Gets the minimum value of a given Column/Field Name within the given Table Name
  339.         /// </summary>
  340.         /// <param name="table">Name of the table to lookup</param>
  341.         /// <param name="key">Name of the Column/Field to lookup</param>
  342.         /// <returns>The minimum value reported by MySQL</returns>
  343.         public int GetMinValue(string table, string key)
  344.         {
  345.             if (!Connected)
  346.                 return 0;
  347.  
  348.             string query = String.Format("SELECT MIN({0}) FROM `{1}`", key, table);
  349.  
  350.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  351.             cmd.CommandText = query;
  352.  
  353.             OdbcDataReader reader = cmd.ExecuteReader();
  354.  
  355.             int min = 0;
  356.  
  357.             if (reader.HasRows)
  358.             {
  359.                 while (reader.Read())
  360.                 {
  361.                     min = reader.GetInt32(0);
  362.                 }
  363.  
  364.                 reader.Close();
  365.                 reader.Dispose();
  366.             }
  367.  
  368.             cmd.Dispose();
  369.  
  370.             return min;
  371.         }
  372.  
  373.         /// <summary>
  374.         /// Gets the maximum value of a given Column/Field Name within the given Table Name
  375.         /// </summary>
  376.         /// <param name="table">Name of the table to lookup</param>
  377.         /// <param name="key">Name of the Column/Field to lookup</param>
  378.         /// <returns>The maximum value reported by MySQL</returns>
  379.         public int GetMaxValue(string table, string key)
  380.         {
  381.             if (!Connected)
  382.                 return 0;
  383.  
  384.             string query = String.Format("SELECT MAX({0}) FROM `{1}`", key, table);
  385.  
  386.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  387.             cmd.CommandText = query;
  388.  
  389.             OdbcDataReader reader = cmd.ExecuteReader();
  390.  
  391.             int max = 0;
  392.  
  393.             if (reader.HasRows)
  394.             {
  395.                 while (reader.Read())
  396.                 {
  397.                     object obj = reader.GetValue(0);
  398.  
  399.                     try
  400.                     {
  401.                         max = Convert.ToInt32(obj);
  402.                     }
  403.                     catch
  404.                     { }
  405.                 }
  406.  
  407.                 reader.Close();
  408.                 reader.Dispose();
  409.             }
  410.  
  411.             cmd.Dispose();
  412.  
  413.             return max;
  414.         }
  415.  
  416.         /// <summary>
  417.         /// Gets the count value of a given Column/Field Name within the given Table Name
  418.         /// </summary>
  419.         /// <param name="table">Name of the table to lookup</param>
  420.         /// <param name="key">Name of the Column/Field to lookup</param>
  421.         /// <param name="searchKey">Left-side of the 'WHERE' argument</param>
  422.         /// <param name="searchVal">Right-side of the 'WHERE' argument</param>
  423.         /// <returns>The count value reported by MySQL</returns>
  424.         public int GetCount(string table, string key, string searchKey, string searchVal)
  425.         {
  426.             if (!Connected)
  427.                 return 0;
  428.  
  429.             string query = String.Format("SELECT COUNT({0}) FROM `{1}` WHERE {2}='{3}'", key, table, searchKey, searchVal);
  430.  
  431.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  432.             cmd.CommandText = query;
  433.  
  434.             OdbcDataReader reader = cmd.ExecuteReader();
  435.  
  436.             int count = 0;
  437.  
  438.             if (reader.HasRows)
  439.             {
  440.                 while (reader.Read())
  441.                 {
  442.                     count = reader.GetInt32(0);
  443.                 }
  444.  
  445.                 reader.Close();
  446.                 reader.Dispose();
  447.             }
  448.  
  449.             cmd.Dispose();
  450.  
  451.             return count;
  452.         }
  453.  
  454.         /// <summary>
  455.         /// Updates the given Column/Field data within the given Table Name using the given Value
  456.         /// </summary>
  457.         /// <param name="table">Name of the table to lookup</param>
  458.         /// <param name="key">Name of the Column/Field to lookup</param>
  459.         /// <param name="val">Value to set</param>
  460.         /// <param name="searchKey">Left-side of the 'WHERE' argument</param>
  461.         /// <param name="searchVal">Right-side of the 'WHERE' argument</param>
  462.         /// <returns>True if successful</returns>
  463.         public bool SetData(string table, string key, string val, string searchKey, string searchVal)
  464.         {
  465.             if (!Connected)
  466.                 return false;
  467.  
  468.             string query = String.Format("UPDATE `{0}` SET {1}='{2}' WHERE {3}='{4}'", table, key, val, searchKey, searchVal);
  469.  
  470.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  471.             cmd.CommandText = query;
  472.  
  473.             bool ret = (cmd.ExecuteNonQuery() > 0);
  474.  
  475.             cmd.Dispose();
  476.  
  477.             return ret;
  478.         }
  479.  
  480.         /// <summary>
  481.         /// Sets the given Column/Field data within the given Table Name using the given Data
  482.         /// </summary>
  483.         /// <param name="table">Name of the table to lookup</param>
  484.         /// <param name="data">List of "Column/Field Name" => "Value" data to insert or replace</param>
  485.         /// <param name="replace">If true, will replace existing data of the same keys, if exists.</param>
  486.         /// <returns>True if successful</returns>
  487.         public bool PutData(string table, MySQLData[] data, bool replace)
  488.         {
  489.             if (!Connected)
  490.                 return false;
  491.  
  492.             string keys = String.Empty;
  493.             string values = String.Empty;
  494.  
  495.             int count = data.Length;
  496.             int index = 0;
  497.             for (int i = 0; i < count; i++)
  498.             {
  499.                 keys += data[i].Key;
  500.  
  501.                 if (index < count - 1)
  502.                     keys += ", ";
  503.  
  504.                 values += "'" + data[i].Value + "'";
  505.  
  506.                 if (index < count - 1)
  507.                     values += ", ";
  508.  
  509.                 index++;
  510.             }
  511.  
  512.             string query = String.Format("{0} INTO `{1}` ({2}) VALUES ({3})", (replace ? "REPLACE" : "INSERT"), table, keys, values);
  513.  
  514.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  515.             cmd.CommandText = query;
  516.  
  517.             bool ret = (cmd.ExecuteNonQuery() > 0);
  518.  
  519.             cmd.Dispose();
  520.  
  521.             return ret;
  522.         }
  523.  
  524.         /// <summary>
  525.         /// Removes a row from the given Table Name using the given search arguments
  526.         /// </summary>
  527.         /// <param name="table">Name of the table to lookup</param>
  528.         /// <param name="searchKey">Left-side of the 'WHERE' argument</param>
  529.         /// <param name="searchVal">Right-side of the 'WHERE' argument</param>
  530.         /// <returns></returns>
  531.         public bool RemoveData(string table, string searchKey, string searchVal)
  532.         {
  533.             if (!Connected)
  534.                 return false;
  535.  
  536.             string query = String.Format("DELETE FROM `{0}` WHERE {1}='{2}'", table, searchKey, searchVal);
  537.  
  538.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  539.             cmd.CommandText = query;
  540.  
  541.             bool ret = (cmd.ExecuteNonQuery() > 0);
  542.  
  543.             cmd.Dispose();
  544.  
  545.             return ret;
  546.         }
  547.  
  548.         /// <summary>
  549.         /// Searches and returns a MySQLResult collection within the given Table Name using the given search arguments
  550.         /// </summary>
  551.         /// <param name="table">Name of the table to lookup</param>
  552.         /// <param name="keys">List of Colum/Field names to return data for (Seperated by commas ',')</param>
  553.         /// <param name="searchKey">Left-side of the 'WHERE' argument</param>
  554.         /// <param name="searchVal">Right-side of the 'WHERE' argument</param>
  555.         /// <param name="order">The Column/Field Name to order the results by</param>
  556.         /// <returns>MySQLResult Collection containing the results for this query</returns>
  557.         public MySQLResult[] SearchData(string table, string keys, string searchKey, string searchVal, string order)
  558.         {
  559.             if (!Connected)
  560.                 return new MySQLResult[0];
  561.  
  562.             string query = String.Format("SELECT {0} FROM `{1}` WHERE {2}='{3}' ORDER BY {4}", keys, table, searchKey, searchVal, order);
  563.  
  564.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  565.             cmd.CommandText = query;
  566.  
  567.             OdbcDataReader reader = cmd.ExecuteReader();
  568.  
  569.             List<MySQLResult> tmp = new List<MySQLResult>();
  570.  
  571.             if (reader.HasRows)
  572.             {
  573.  
  574.                 while (reader.Read())
  575.                 {
  576.                     for (int i = 0; i < reader.FieldCount; i++)
  577.                     {
  578.                         string key = reader.GetName(i);
  579.                         object obj = reader.GetValue(i);
  580.  
  581.                         tmp.Add(new MySQLResult(i, key, obj));
  582.                     }
  583.                 }
  584.  
  585.                 reader.Close();
  586.                 reader.Dispose();
  587.             }
  588.  
  589.             cmd.Dispose();
  590.  
  591.             MySQLResult[] ret = new MySQLResult[tmp.Count];
  592.  
  593.             for (int i = 0; i < tmp.Count; i++)
  594.             {
  595.                 ret[i] = tmp[i];
  596.             }
  597.  
  598.             tmp.Clear();
  599.  
  600.             return ret;
  601.         }
  602.  
  603.         /// <summary>
  604.         /// Performs a standard MySQL custom query
  605.         /// </summary>
  606.         /// <param name="query">Custom query text</param>
  607.         /// <returns>Total number of affected rows</returns>
  608.         public int Query(string query)
  609.         {
  610.             if (!Connected)
  611.                 return 0;
  612.  
  613.             OdbcCommand cmd = _CONNECTION.CreateCommand();
  614.             cmd.CommandText = query;
  615.  
  616.             int ret = cmd.ExecuteNonQuery();
  617.  
  618.             cmd.Dispose();
  619.  
  620.             return ret;
  621.         }
  622.  
  623.         /// <summary>
  624.         /// Closes and Disposes the instance of Connection
  625.         /// </summary>
  626.         public void Close()
  627.         {
  628.             if (!Connected)
  629.             {
  630.                 _CONNECTION = null;
  631.                 return;
  632.             }
  633.  
  634.             _CONNECTION.Close();
  635.             _CONNECTION.Dispose();
  636.             _CONNECTION = null;
  637.         }
  638.  
  639.         public override string ToString()
  640.         {
  641.             return String.Format("[{0}] => '{1}'", _IP, Connected ? _CONNECTION.State.ToString() : "Disconnected");
  642.         }
  643.     }
  644. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement