Advertisement
Guest User

Untitled

a guest
Feb 3rd, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.73 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6.  
  7. using MySql.Data.MySqlClient;
  8.  
  9. namespace GameServer
  10. {
  11.     public static class DB
  12.     {
  13.         private static string strConnection;
  14.  
  15.         static void dbConnection_StateChange(object usr, StateChangeEventArgs ev)
  16.         {
  17.             if (ev.CurrentState == ConnectionState.Broken)
  18.             {
  19.                 System.Threading.Thread.Sleep(1000);
  20.                 dbConnection.Close();
  21.             }
  22.  
  23.             if (ev.CurrentState == ConnectionState.Closed)
  24.             {
  25.                 System.Threading.Thread.Sleep(1000);
  26.  
  27.                 Log.WriteLine("Reconnecting to SQL Server 1...");
  28.                 dbConnection = new MySqlConnection(strConnection);
  29.                 dbConnection.StateChange += new System.Data.StateChangeEventHandler(dbConnection_StateChange);
  30.                 System.Threading.Thread.Sleep(2000);
  31.                 dbConnection.Open();
  32.                 Log.WriteLine("Reconnection to database 1 successful.");
  33.             }
  34.         }
  35.  
  36.         private static MySqlConnection dbConnection;
  37.         #region Database connection management
  38.         /// <summary>
  39.         /// Opens connection to the MySQL database with the supplied parameters, and returns a 'true' boolean when the connection has succeeded. Requires MySQL MySql 5.1 driver to be installed.
  40.         /// </summary>
  41.         /// <param name="dbHost">The hostname/IP address where the database server is located.</param>
  42.         /// <param name="dbPort">The port the database server is running on.</param>
  43.         /// <param name="dbName">The name of the data</param>
  44.         /// <param name="dbUsername">The username for authentication with the data</param>
  45.         /// <param name="dbPassword">The pasword for authentication with the data</param>
  46.         public static bool openConnection(string dbHost, int dbPort, string dbName, string dbUsername, string dbPassword, int dbPoolsize)
  47.         {
  48.             try
  49.             {
  50.                 Log.WriteLine("Connecting to " + dbName + " at " + dbHost + ":" + dbPort + " for user '" + dbUsername + "'");
  51.                 strConnection = "Server=" + dbHost + ";Port=" + dbPort + ";Database=" + dbName + ";User=" + dbUsername + ";Password=" + dbPassword + ";Pooling=Yes;Min pool size=0;Max pool size=" + dbPoolsize + ";Connection timeout=1;";
  52.                 dbConnection = new MySqlConnection(strConnection);
  53.                 dbConnection.StateChange += new System.Data.StateChangeEventHandler(dbConnection_StateChange);
  54.                 dbConnection.Open();
  55.                 if (dbConnection.State == ConnectionState.Open)
  56.                 {
  57.                     Log.WriteLine("Connection to database successfull.");
  58.                     return true;
  59.                 }
  60.                 else
  61.                 {
  62.                     Log.WriteError("Failed to connect to " + dbName + " at " + dbHost + ":" + dbPort + " for user '" + dbUsername + "'");
  63.                     return false;
  64.                 }
  65.             }
  66.  
  67.             catch (Exception ex)
  68.             {
  69.                 Log.WriteError("Failed to connect! Error thrown was: " + ex.Message);
  70.                 return false;
  71.             }
  72.         }
  73.         /// <summary>
  74.         /// Closes connection with the MySQL data Any errors are ignored.
  75.         /// </summary>
  76.         public static void closeConnection()
  77.         {
  78.             Log.WriteLine("Closing database connection...");
  79.             try
  80.             {
  81.                 dbConnection.Close();
  82.                 Log.WriteLine("Database connection closed.");
  83.             }
  84.             catch { Log.WriteError("No database connection."); }
  85.         }
  86.         #endregion
  87.  
  88.         #region Database data manipulation
  89.         /// <summary>
  90.         /// Executes a SQL statement on the data
  91.         /// </summary>
  92.         /// <param name="Query">The SQL statement to be executed. Default SQL syntax.</param>
  93.         public static void runQuery(string Query)
  94.         {
  95.             try
  96.             {
  97.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  98.                 {
  99.                     c.Open();
  100.                     using (MySqlCommand cmd = c.CreateCommand())
  101.                     {
  102.                         cmd.CommandText = Query;
  103.                         cmd.ExecuteNonQuery();
  104.                     }
  105.                 }
  106.             }
  107.             catch (Exception ex) { Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'"); }
  108.         }
  109.         #endregion
  110.  
  111.         #region Database data retrieval
  112.         #region runRead
  113.         /// <summary>
  114.         /// Performs a SQL query and returns the first selected field as string. Other fields are ignored.
  115.         /// </summary>
  116.         /// <param name="Query">The SQL query that selects a field.</param>
  117.         public static string runRead(string Query)
  118.         {
  119.             try
  120.             {
  121.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  122.                 {
  123.                     c.Open();
  124.                     using (MySqlCommand cmd = c.CreateCommand())
  125.                     {
  126.                         cmd.CommandText = Query + " LIMIT 1";
  127.                         return cmd.ExecuteScalar().ToString();
  128.                     }
  129.                 }
  130.             }
  131.             catch (Exception ex)
  132.             {
  133.                 Log.WriteLine("Error '" + ex.Message + "' at '" + Query + "'");
  134.                 return "";
  135.             }
  136.         }
  137.         /// <summary>
  138.         /// Performs a SQL query and returns the first selected field as integer. Other fields are ignored.
  139.         /// </summary>
  140.         /// <param name="Query">The SQL query that selects a field.</param>
  141.         /// <param name="Tick">Just to differ the runRead functions; supply a null if you want to use this overload.</param>
  142.         public static int runRead(string Query, object Tick)
  143.         {
  144.             try
  145.             {
  146.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  147.                 {
  148.                     c.Open();
  149.                     using (MySqlCommand cmd = c.CreateCommand())
  150.                     {
  151.                         cmd.CommandText = Query + " LIMIT 1";
  152.                         return int.Parse(cmd.ExecuteScalar().ToString());
  153.                     }
  154.                 }
  155.             }
  156.             catch (Exception ex)
  157.             {
  158.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  159.                 return 0;
  160.             }
  161.         }
  162.         #endregion
  163.         #region runReadColumn
  164.         /// <summary>
  165.         /// Performs a SQL query and returns all vertical matching fields as a String array. Only the first supplied columname is looked for.
  166.         /// </summary>
  167.         /// <param name="Query">The SQL query that selects a column.</param>
  168.         /// <param name="maxResults">Adds as LIMIT to the query. Using this, the array will never return more than xx fields in of the column. When maxResults is supplied as 0, then there is no max limit.</param>
  169.         public static string[] runReadColumn(string Query, int maxResults)
  170.         {
  171.             if (maxResults > 0)
  172.                 Query += " LIMIT " + maxResults;
  173.  
  174.             try
  175.             {
  176.                 ArrayList builder = new ArrayList();
  177.  
  178.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  179.                 {
  180.                     c.Open();
  181.                     using (MySqlCommand cmd = c.CreateCommand())
  182.                     {
  183.                         cmd.CommandText = Query;
  184.                         using (MySqlDataReader reader = cmd.ExecuteReader())
  185.                         {
  186.                             while (reader.Read())
  187.                             {
  188.                                 try { builder.Add(reader[0].ToString()); }
  189.                                 catch { builder.Add(""); }
  190.                             }
  191.                             reader.Close();
  192.                             return (string[])builder.ToArray(typeof(string));
  193.                         }
  194.                     }
  195.                 }
  196.             }
  197.  
  198.             catch (Exception ex)
  199.             {
  200.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  201.                 return new string[0];
  202.             }
  203.         }
  204.         /// <summary>
  205.         /// Performs a SQL query and returns all vertical matching fields as an Integer array. Only the first supplied columname is looked for.
  206.         /// </summary>
  207.         /// <param name="Query">The SQL query that selects a column.</param>
  208.         /// <param name="maxResults">Adds as LIMIT to the query. Using this, the array will never return more than xx fields in of the column. When maxResults is supplied as 0, then there is no max limit.</param>
  209.         /// <param name="Tick">Just to differ the runReadColumn functions; supply a null if you want to use this overload.</param>
  210.         public static int[] runReadColumn(string Query, int maxResults, object Tick)
  211.         {
  212.             if (maxResults > 0)
  213.                 Query += " LIMIT " + maxResults;
  214.             try
  215.             {
  216.                 ArrayList builder = new ArrayList();
  217.  
  218.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  219.                 {
  220.                     c.Open();
  221.                     using (MySqlCommand cmd = c.CreateCommand())
  222.                     {
  223.                         cmd.CommandText = Query;
  224.                         using (MySqlDataReader reader = cmd.ExecuteReader())
  225.                         {
  226.                             while (reader.Read())
  227.                             {
  228.                                 try { builder.Add(reader.GetInt32(0)); }
  229.                                 catch { builder.Add(""); }
  230.                             }
  231.                             reader.Close();
  232.                             return (int[])builder.ToArray(typeof(int));
  233.                         }
  234.                     }
  235.                 }
  236.             }
  237.  
  238.             catch (Exception ex)
  239.             {
  240.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  241.                 return new int[0];
  242.             }
  243.         }
  244.         #endregion
  245.         #region runReadRow
  246.         /// <summary>
  247.         /// Performs a SQL query and returns the selected in the first found row as a String array. Useable for only one row.
  248.         /// </summary>
  249.         /// <param name="Query">The SQL query that selects a row and the fields to get. LIMIT 1 is added.</param>
  250.         public static string[] runReadRow(string Query)
  251.         {
  252.             try
  253.             {
  254.                 ArrayList builder = new ArrayList();
  255.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  256.                 {
  257.                     c.Open();
  258.                     using (MySqlCommand cmd = c.CreateCommand())
  259.                     {
  260.                         cmd.CommandText = Query + " LIMIT 1";
  261.                         using (MySqlDataReader reader = cmd.ExecuteReader())
  262.                         {
  263.                             while (reader.Read())
  264.                             {
  265.                                 for (int i = 0; i < reader.FieldCount; i++)
  266.                                 {
  267.                                     try { builder.Add(reader[i].ToString()); }
  268.                                     catch { builder.Add(""); }
  269.                                 }
  270.                             }
  271.                             reader.Close();
  272.                             return (string[])builder.ToArray(typeof(string));
  273.                         }
  274.                     }
  275.                 }
  276.             }
  277.  
  278.             catch (Exception ex)
  279.             {
  280.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  281.                 return new string[0];
  282.             }
  283.         }
  284.         /// <summary>
  285.         /// Performs a SQL query and returns the selected in the first found row as an Integer array. Useable for only one row.
  286.         /// </summary>
  287.         /// <param name="Query">The SQL query that selects a row and the fields to get. LIMIT 1 is added.</param>
  288.         /// <param name="Tick">Just to differ the runReadRow functions; supply a null if you want to use this overload.</param>
  289.         public static int[] runReadRow(string Query, object Tick)
  290.         {
  291.             try
  292.             {
  293.                 ArrayList builder = new ArrayList();
  294.  
  295.                 using (MySqlConnection c = new MySqlConnection(strConnection))
  296.                 {
  297.                     c.Open();
  298.                     using (MySqlCommand cmd = c.CreateCommand())
  299.                     {
  300.                         cmd.CommandText = Query + " LIMIT 1";
  301.                         using (MySqlDataReader reader = cmd.ExecuteReader())
  302.                         {
  303.                             while (reader.Read())
  304.                             {
  305.                                 for (int i = 0; i < reader.FieldCount; i++)
  306.                                 {
  307.                                     try { builder.Add(reader.GetInt32(i)); }
  308.                                     catch { builder.Add(""); }
  309.                                 }
  310.                             }
  311.                             reader.Close();
  312.                             return (int[])builder.ToArray(typeof(int));
  313.                         }
  314.                     }
  315.                 }
  316.             }
  317.  
  318.             catch (Exception ex)
  319.             {
  320.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  321.                 return new int[0];
  322.             }
  323.         }
  324.         #endregion
  325.         #endregion
  326.  
  327.         #region Data availability checks
  328.         /// <summary>
  329.         /// Tries to find fields matching the query. When there is at least one result, it returns True and stops.
  330.         /// </summary>
  331.         /// <param name="Query">The SQL query that contains the seeked fields and conditions. LIMIT 1 is added.</param>
  332.         public static bool checkExists(string Query)
  333.         {
  334.             try { return new MySqlCommand(Query + " LIMIT 1", dbConnection).ExecuteReader().HasRows; }
  335.             catch (Exception ex)
  336.             {
  337.                 Log.WriteError("Error '" + ex.Message + "' at '" + Query + "'");
  338.                 return false;
  339.             }
  340.         }
  341.         #endregion
  342.  
  343.         #region Misc
  344.         /// <summary>
  345.         /// Returns a stripslashed copy of the input string.
  346.         /// </summary>
  347.         /// <param name="Query">The string to add stripslashes to.</param>
  348.         public static string Stripslash(string Query)
  349.         {
  350.             try { return Query.Replace(@"\", "\\").Replace("'", "\'").Replace("'", @"`"); }
  351.             catch { return ""; }
  352.         }
  353.         #endregion
  354.     }
  355. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement