Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- // REQUIERE LA REFERENCIA System.Data
- using System.Data;
- // REQUIERE LA REFERENCIA MySql.Data
- using MySql.Data.MySqlClient;
- using System.IO;
- /*
- * CLASE MYSQLCS
- * Agregar al proyecto con using MysqlCS;
- * REQUIERE CAMBIAR LOS PARÁMETROS DE CONEXIÓN
- */
- namespace MysqlCS
- {
- public class Connection
- {
- protected string host = "127.0.0.1";
- protected string port = "3306";
- protected string db = "MI_BASE_DE_DATOS";
- protected string user = "MI_USUARIO";
- protected string pass = "MI_CONTRASEÑA";
- protected MySqlConnection cnn;
- protected MySqlCommand cmd;
- protected string enlace;
- protected bool activo = false;
- /*
- * CONSTRUCTOR
- */
- public Connection()
- {
- try
- {
- enlace =
- "Server=" + host +
- ";Port=" + port +
- ";User ID=" + user +
- ";Database=" + db +
- ";Password=" + pass +
- ";";
- cnn = new MySqlConnection(enlace);
- cnn.Open();
- }
- catch (Exception e)
- {
- Console.WriteLine("ERROR: {0}", e.Message);
- Console.ReadKey();
- // Cierra la aplicación en caso de ERROR
- Environment.Exit(1);
- }
- }
- /*
- * COUNT ALL ROWS
- * Devuelve total de filas de una tabla
- * @param string
- * @return int
- */
- public int count_all_rows(string tabla)
- {
- int count = 0;
- using(cmd = new MySqlCommand("SELECT COUNT(*) FROM " + tabla, cnn))
- {
- count = Convert.ToInt32(cmd.ExecuteScalar());
- cmd.Dispose();
- }
- return count;
- }
- /*
- * QUERY
- * Ejecuta una solicitud al servidor
- * @param string
- * @return void
- */
- public void query(string solicitud)
- {
- cmd = new MySqlCommand(solicitud, cnn);
- activo = true;
- }
- /*
- * DATATABLE
- * Devuelve los datos de una solicitud de la función QUERY
- * Los datos retornados son del tipo DataTable (System.Data)
- * @param
- * @return DataTable
- */
- public DataTable datatable()
- {
- if (activo)
- {
- DataTable data = new DataTable();
- data.Load(cmd.ExecuteReader());
- cmd.Dispose();
- activo = false;
- return data;
- }
- else
- return new DataTable();
- }
- /*
- * FIRST DATA
- * Devuelve la primera fila de una tabla después de una solicitud con QUERY
- * El resultado se almacena en un DataRow (System.Data)
- * @param
- * @return DataRow
- */
- public DataRow first_data()
- {
- if (activo)
- {
- DataTable data = datatable();
- activo = false;
- if (data.Rows.Count > 0)
- return data.Rows [0];
- else
- return null;
- }
- return null;
- }
- /*
- * ONLY EXEC
- * Ejecuta una solicitud QUERY y devuelve el Identificador de INSERT
- * @param
- * @return int
- */
- public int only_exec()
- {
- int id = 0;
- if (activo)
- {
- cmd.ExecuteNonQuery();
- id = (int)cmd.LastInsertedId;
- cmd.Dispose();
- }
- activo = false;
- return id;
- }
- /*
- * DESTRUCTOR
- * Libera la memoria y cierra la conexión
- * @param
- * @return
- */
- ~Connection()
- {
- cnn.Close();
- }
- }
- }
- /* Licencia MIT - OOSJ */
Add Comment
Please, Sign In to add comment