[Include] Easy MySQL - Simplifica el uso de queries en MySQL
#1

Easy - MySQL


En general:

Bueno, este include ya lo habнa publicado en la secciуn de inglйs, pero bueno como se tambiйn espaсol pense en por quй no publicar en esta secciуn tambiйn.
Bбsicamente, este include simplifca algunos queries que son muy empleados por la mayorнa(ojo hay algunas cosas que obviamente faltan), con este include te ahorrarбs el uso de strcat para concatenar strings y obtener ese error que te dice que alguna string es demasiado larga o alguna cosa por el estilo.



Ventajas:

- Primero que todo, como ya dije arriba realmente simplifica el uso de queries pues este include une las partes que conforman al query internamente.
- Si alguna vez usaste Y_INI o algъn otro sistema parecido esto te resultarб muy simple.
- Puedes guardar una gran cantidad de datos en la base de datos sin preocuparte en concatenar varias partes a la vez.
- Puedes crear y manejar tablas desde el script.
- No necesitas ser un genio en MySQL para usar esto.


Funciones:

Код:
Added in v2.0

native SQL::Open(SQL::qtypes:type, const table[], const column[] = "", columnID = -1, connectionHandle = 1);
native SQL::OpenEx(SQL::qtypes:type, const table[], const column[] = "", columnID[] = "", connectionHandle = 1)
native SQL::ToggleAutoIncrement(handle, bool:toggle);
native SQL::WriteFloat(handle, const field[], Float:value);
native SQL::WriteInt(handle, const field[], value);
native SQL::WriteString(handle, const field[], const value[]);
native SQL::ReadInt(handle, const field[], &dest);
native SQL::ReadFloat(handle, const field[], &Float:dest);
native SQL::ReadString(handle, const field[], dest[], len = sizeof(dest));
native SQL::Close(handle);
native SQL::Connect(const host[], const user[], const database[], const password[], bool:debugging = false, port = 3306, bool:autoreconnect = true, pool_size = 2);
native SQL::DeleteRow(const table[], const column[], columnID, connectionHandle = 1);
native SQL::DeleteRowEx(const table[], const column[], columnID[], connectionHandle = 1);
native SQL::GetIntEntry(const table[], const field[], const column[], columnID, connectionHandle = 1);
native Float:SQL::GetFloatEntry(const table[], const field[], const column[], columnID, connectionHandle = 1);
native SQL::GetStringEntry(const table[], const field[], const column[], columnID, dest[], len = sizeof(dest), connectionHandle = 1);
native SQL::GetStringEntryEx(const table[], const field[], const column[], const scolumn[], dest[], len = sizeof(dest), connectionHandle = 1)
native SQL::GetIntEntryEx(const table[], const field[], const column[], scolumn[], connectionHandle = 1);
native Float:SQL::GetFloatEntryEx(const table[], const field[], const column[], scolumn[], connectionHandle = 1);
native SQL::CreateTable(const tablename[], connectionHandle = 1);
native SQL::AddTableEntry(handle, const field[], SQL::datatypes: type = SQL_TYPE_INT, maxlength = 11, bool:auto_increment = false, bool:setprimary = false);
native SQL::SetIntEntry(const table[], const field[], value, const column[], columnID, connectionHandle = 1);
native SQL::SetIntEntryEx(const table[], const field[], value, const column[], columnID[], connectionHandle = 1);
native SQL::SetFloatEntry(const table[], const field[], Float:value, const column[], columnID, connectionHandle = 1);
native SQL::SetFloatEntryEx(const table[], const field[], Float:value, const column[], columnID[], connectionHandle = 1);
native SQL::SetStringEntry(const table[], const field[], const value[], const column[], columnID, bool:use_real_escape = true, connectionHandle = 1);
native SQL::SetStringEntryEx(const table[], const field[], const value[], const column[], columnID[], bool:use_real_escape = true, connectionHandle = 1);
native SQL::ExistsTable(const tablename[], connectionHandle = 1);
native SQL::CountRows(const tablename[], connectionHandle = 1);
native SQL::CountTables(connectionHandle = 1);
native SQL::DropTable(const tablename[], connectionHandle = 1);
native SQL::DeleteColumn(const table[], const column[], connectionHandle = 1);
native SQL::Begin(connectionHandle = 1)
native SQL::Commit(connectionHandle = 1)
Sistema de registraciуn e inicio de sesiуn usando este include:


PHP код:
/*
 *  Simple sistema de registraciуn e inicio de sesiуn usando easy-mysql.inc
*/
#include <a_samp>
#include <easy-mysql>
main()
{
    
}
#define mysql_host    "localhost"
#define mysql_user    "root"
#define mysql_db        "server"
#define mysql_pass         ""
#define mysql_debugging_enabled             (true)
#define DIALOG_LOGIN 0
#define DIALOG_REGISTER 1
enum p_info
{
    
p_id,
    
p_name[24],
    
p_password[64],
    
p_score,
    
Float:p_posx,
    
Float:p_posy,
    
Float:p_posz,
    
p_loggedin
};
new 
UserInfo[MAX_PLAYERS][p_info];
    
stock ret_pName(playerid)
{
    new 
name[24];
    
GetPlayerName(playeridnamesizeof(name));
    return 
name;
}
public 
OnGameModeInit()
{
    
//Conecciуn a la base MySQL
    
SQL::Connect(mysql_hostmysql_usermysql_dbmysql_pass);
    
    
//Verificando si la table "players" existe
    
if(!SQL::ExistsTable("players"))
    {
        
//Si no existe, entonces el script crearб una tabla llamada "players"
        
new handle SQL::Open(SQL::CREATE"players"); //Abrimos un 'handle' para crear la tabla.
        
SQL::AddTableEntry(handle"p_id"SQL_TYPE_INT11true);
        
SQL::AddTableEntry(handle"p_name"SQL_TYPE_VCHAR24);
        
SQL::AddTableEntry(handle"p_password"SQL_TYPE_VCHAR64);
        
SQL::AddTableEntry(handle"p_score"SQL_TYPE_INT);
        
SQL::AddTableEntry(handle"p_posx"SQL_TYPE_FLOAT);
        
SQL::AddTableEntry(handle"p_posy"SQL_TYPE_FLOAT);
        
SQL::AddTableEntry(handle"p_posz"SQL_TYPE_FLOAT);
        
SQL::Close(handle);//Cerramos el 'handle' que abrimos previamente.
    
}
    return 
1;
}
public 
OnPlayerConnect(playerid)
{
    
UserInfo[playerid][p_loggedin] = 0UserInfo[playerid][p_score] = 0;  UserInfo[playerid][p_posx] = 1958.3783;
    
UserInfo[playerid][p_posy] = 1343.1572UserInfo[playerid][p_posz] = 15.3746
    if(
SQL::RowExistsEx("players""p_name"ret_pName(playerid))) //Verificamos si el nombre del jugador existe en la tabla 'players'
    
{
        
//Obtenemos la contraseсa y el ID en la base de datos del jugador.
        
new handle SQL::OpenEx(SQL::READ"players""p_name"ret_pName(playerid));
        
SQL::ReadString(handle"p_password"UserInfo[playerid][p_password], 64);
        
SQL::ReadInt(handle"p_id"UserInfo[playerid][p_id]);
        
SQL::Close(handle);
        
//Mostramos el diбlogo de ingreso.
        
ShowPlayerDialog(playeridDIALOG_LOGINDIALOG_STYLE_PASSWORD"{0080FF}Login""Please input your password below to log in.""Login""Exit");
    }
    else
    {
        
//Si no estб registrado le mostramos el diбlogo de registro.
        
ShowPlayerDialog(playeridDIALOG_REGISTERDIALOG_STYLE_PASSWORD"{0080FF}Register""Please input a password below to register in.""Login""Exit");
    }
    return 
1;
}
public 
OnPlayerSpawn(playerid)
{
    
SetPlayerPos(playeridUserInfo[playerid][p_posx], UserInfo[playerid][p_posy], UserInfo[playerid][p_posz]);
    return 
1;
}
public 
OnPlayerDisconnect(playeridreason)
{
    if(
UserInfo[playerid][p_loggedin] == 1)
    {
        
//Si el jugador ingresу a su cuenta, guardamos su informaciуn.
        
GetPlayerPos(playeridUserInfo[playerid][p_posx], UserInfo[playerid][p_posy], UserInfo[playerid][p_posz]);
        new 
handle SQL::Open(SQL::UPDATE"players""p_id"UserInfo[playerid][p_id]);
        
SQL::WriteInt(handle"p_score"GetPlayerScore(playerid));
        
SQL::WriteFloat(handle"p_posx"UserInfo[playerid][p_posx]);
        
SQL::WriteFloat(handle"p_posy"UserInfo[playerid][p_posy]);
        
SQL::WriteFloat(handle"p_posz"UserInfo[playerid][p_posz]);
        
SQL::Close(handle);
    }
    return 
1;
}
public 
OnDialogResponse(playeriddialogidresponselistiteminputtext[])
{
    switch(
dialogid)
    {
        case 
DIALOG_REGISTER:
        {
            if(!
response) return Kick(playerid);
            if(
strlen(inputtext) < 5)
            {
                
ShowPlayerDialog(playeridDIALOG_REGISTERDIALOG_STYLE_PASSWORD"{0080FF}Register""Please input a password below to register in.""Login""Exit");
                return 
1;
            }
            
SHA256_PassHash(inputtext""UserInfo[playerid][p_password], 64);
            new 
handle SQL::Open(SQL::INSERT"players");
            
SQL::ToggleAutoIncrement(handletrue);//Activa el auto incremento es decir que esta la funciуn SQL::Close retornarб cache_insert_id();
            
SQL::WriteString(handle"p_name"ret_pName(playerid));
            
SQL::WriteString(handle"p_password"UserInfo[playerid][p_password]);
            
SQL::WriteInt(handle"p_score"0);
            
SQL::WriteFloat(handle"p_posx"0.0);
            
SQL::WriteFloat(handle"p_posy"0.0);
            
SQL::WriteFloat(handle"p_posz"0.0);
            
UserInfo[playerid][p_id] = SQL::Close(handle); 
            
SendClientMessage(playerid, -1"Successfully registered in!");
            
UserInfo[playerid][p_loggedin] = 1;
        }
        case 
DIALOG_LOGIN:
        {
            if(!
responseKick(playerid); 
            new 
hash[64];
            
SHA256_PassHash(inputtext""hash64);
            if(!
strcmp(hashUserInfo[playerid][p_password]))
            { 
                
//Cargamos la informaciуn del jugador.
                
new handle SQL::Open(SQL::READ"players""p_id"UserInfo[playerid][p_id]);
                
SQL::ReadInt(handle"p_score"UserInfo[playerid][p_score]);
                
SQL::ReadFloat(handle"p_posx"UserInfo[playerid][p_posx]);
                
SQL::ReadFloat(handle"p_posy"UserInfo[playerid][p_posy]);
                
SQL::ReadFloat(handle"p_posz"UserInfo[playerid][p_posz]);
                
SQL::Close(handle);//You must close the handle.
                
SetPlayerScore(playeridUserInfo[playerid][p_score]);
                
UserInfo[playerid][p_loggedin] = 1;
                
SendClientMessage(playerid, -1"Successfully logged in!");
                
            }
            else 
            {
                
ShowPlayerDialog(playeridDIALOG_LOGINDIALOG_STYLE_PASSWORD"{0080FF}Login""Please input your password below to log in.""Login""Exit");
            }
        }
    }
    return 
1;

Constantes:

Код:
SQL_TYPE_INT //Se lo usa para enteros
SQL_TYPE_VCHAR //Se lo usa para strings
SQL_TYPE_FLOAT //Se lo usa para como flotante
SQL_INVALID_HANDLE //Un 'handle' invбlido.
SQL::UPDATE //Lo usas cuando quieres guardar informaciуn, es decir que ya existe un record en la base de datos.
SQL::INSERT //Lo usas para ingresar nueva informaciуn a la base de datos, es decir que no existe un record aun en la base de datos.
SQL::READ //Lo usas para obtener o cargar informaciуn de la base de datos.
SQL::CREATE //Lo usas para crear una nueva tabla.


Creando una tabla.


PHP код:
new handle SQL::Open(SQL::CREATE"players");
SQL::AddTableEntry(handle"p_id"SQL_TYPE_INT11true);
SQL::AddTableEntry(handle"p_name"SQL_TYPE_VCHAR24);
SQL::AddTableEntry(handle"p_password"SQL_TYPE_VCHAR64);
SQL::AddTableEntry(handle"p_score"SQL_TYPE_INT);
SQL::AddTableEntry(handle"p_posx"SQL_TYPE_FLOAT);
SQL::AddTableEntry(handle"p_posy"SQL_TYPE_FLOAT);
SQL::AddTableEntry(handle"p_posz"SQL_TYPE_FLOAT);
SQL::Close(handle); 
Ingresando nueva informaciуn a la base de datos.


PHP код:
new handle SQL::Open(SQL::INSERT"players");
SQL::ToggleAutoIncrement(handletrue);//Toggles auto increment, SQL::Close will return cache_insert_id();
SQL::WriteString(handle"p_name"ret_pName(playerid));
SQL::WriteString(handle"p_password"UserInfo[playerid][p_password]);
SQL::WriteInt(handle"p_score"0);
SQL::WriteFloat(handle"p_posx"0.0);
SQL::WriteFloat(handle"p_posy"0.0);
SQL::WriteFloat(handle"p_posz"0.0);
UserInfo[playerid][p_id] = SQL::Close(handle); 
Guardando informaciуn en la base de datos.

PHP код:
new handle SQL::Open(SQL::UPDATE"players""p_id"UserInfo[playerid][p_id]);
SQL::WriteInt(handle"p_score"GetPlayerScore(playerid));
SQL::WriteFloat(handle"p_posx"UserInfo[playerid][p_posx]);
SQL::WriteFloat(handle"p_posy"UserInfo[playerid][p_posy]);
SQL::WriteFloat(handle"p_posz"UserInfo[playerid][p_posz]);
SQL::Close(handle); 

"Leyendo informaciуn de la base de datos.


PHP код:
new handle SQL::Open(SQL::READ"players""p_id"UserInfo[playerid][p_id]);
SQL::ReadInt(handle"p_score"UserInfo[playerid][p_score]);
SQL::ReadFloat(handle"p_posx"UserInfo[playerid][p_posx]);
SQL::ReadFloat(handle"p_posy"UserInfo[playerid][p_posy]);
SQL::ReadFloat(handle"p_posz"UserInfo[playerid][p_posz]);
SQL::Close(handle);//Debes cerrar el 'handle' abierto.. 
Si usas la funciуn SQL::Open o SQL::OpenEx debes usar al final
Код:
native SQL::Close(handle)
Para que se ejecute la acciуn.


Obviamente me falta documentar las demбs funciones pero lo harй luego.

He aсadido dos funciones mбs para realizar transacciones:

Код:
native SQL::Begin(connectionHandle = 1)
native SQL::Commit(connectionHandle = 1)
Descarga:

V 2.0

Necesitas el plugin de MySQL de BlueG

MySQL Plugin

Si tienes alguna duda, sugerencia, reporte o alguna cosa publica abajo, gracias.
Reply
#2

Edit:

Estб bueno el include, pero deberнas dejar tambiйn un ejemplo para borrar una tabla/columna, saludos.
Reply
#3

Quote:
Originally Posted by LatinZ
Посмотреть сообщение
Estб bueno el include, pero deberнas dejar tambiйn un ejemplo para borrar una tabla, saludos.
Si, tienes razуn aun me falta documentar las funciones, pero bueno aquн va:

Si tuviera una tabla llamada 'players' y la quisiera borrar entonces simplemente harнa esto:


PHP код:
SQL::DropTable("players"); 
Y listo.

Saludos.
Reply
#4

Tiene un bug que causa crash y tira el servidor.

Quote:

[07:09:33] [ERROR] ID: 1064 - Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 - Callback - - Query: UPDATE...
[07:09:33] [debug] Server crashed while executing LEP.amx

Cuando hay muchos valores que guardar tira crash, hay que guardar por partes.
Reply
#5

Quote:
Originally Posted by LatinZ
Посмотреть сообщение
Tiene un bug que causa crash y tira el servidor.



Cuando hay muchos valores que guardar tira crash, hay que guardar por partes.
No es un bug, si revisas el include, hay una parte que dice
PHP код:
#define SQL_MAX_QUERY_LENGTH                (4096) 
Si vas a usar muchos valores entonces aumenta ese lнmite, aunque supongo que estбs intentando utilizar mбs de 100 valores eh... Podrнas colocar 8192 o algъn valor mбs alto.
Reply
#6

Un gran trabajo definitivamente, una pena que la gente no sepa usar SQL lo suficientemente bien, pero seguro que este .inc le facilitarб la vida a mбs de uno.

Lo ъnico malo son las queries en un solo hilo pero es comprensible, el cуdigo se ve todo muy ordenado, hace mucho tiempo que no se ven cosas asн por la secciуn espaсola.

Buen trabajo y de mi parte.

EDIT
Por cierto, corrнgeme si me equivoco, pero el error del input line too long se puede corregir de esta manera (al menos yo siempre lo he hecho asн):
PHP код:
format(stringsizeof(string),
    
"A BIG BIG BIG BIG BIG BIG LINE \
    LINE EXAMPLE %d %d %d %d %d"
,
    
var1,
    
var2,
    
var3,
    
var4,
    
var5
); 
Nunca he tenido problemas haciendo esto en PAWNO. Divides la lнnea en dos o mбs partes mбs cortas y el error... Ўvoilа!
Reply
#7

Quote:
Originally Posted by RIDE2DAY
Посмотреть сообщение
Un gran trabajo definitivamente, una pena que la gente no sepa usar SQL lo suficientemente bien, pero seguro que este .inc le facilitarб la vida a mбs de uno.

Lo ъnico malo son las queries en un solo hilo pero es comprensible, el cуdigo se ve todo muy ordenado, hace mucho tiempo que no se ven cosas asн por la secciуn espaсola.

Buen trabajo y de mi parte.

EDIT
Por cierto, corrнgeme si me equivoco, pero el error del input line too long se puede corregir de esta manera (al menos yo siempre lo he hecho asн):
PHP код:
format(stringsizeof(string),
    
"A BIG BIG BIG BIG BIG BIG LINE \
    LINE EXAMPLE %d %d %d %d %d"
,
    
var1,
    
var2,
    
var3,
    
var4,
    
var5
); 
Nunca he tenido problemas haciendo esto en PAWNO. Divides la lнnea en dos o mбs partes mбs cortas y el error... Ўvoilа!
Si pero de esto se trata este include, de que ya no tengas que hacer eso si no que hagas algo como:

PHP код:
new handle SQL::Open(SQL::UPDATE"foo_table""foo_id"5); 
        
SQL::WriteInt(handle"fooA"913); 
        
SQL::WriteInt(handle"fooB"914); 
        
SQL::WriteInt(handle"fooC"915); 
        
SQL::WriteInt(handle"fooD"916); 
        
SQL::WriteInt(handle"fooE"917); 
        
SQL::WriteInt(handle"fooF"918); 
        
SQL::WriteInt(handle"fooG"919); 
        
SQL::WriteInt(handle"fooH"910); 
        
SQL::WriteFloat(handle"fooI"4.13); 
        
SQL::WriteFloat(handle"fooJ"34.11); 
        
SQL::WriteFloat(handle"fooK"41.111); 
        
SQL::WriteString(handle"fooL""fooX"); 
        
SQL::WriteString(handle"fooM""fooY"); 
        
SQL::WriteString(handle"fooN""fooZ"); 
        
SQL::WriteString(handle"fooO""fooW"); 
        
SQL::WriteString(handle"fooP""fooL"); 
        
SQL::Close(handle); 
Si definitivamente usaste alguna vez YINI, este include te resultarб muy fбcil de usar.
Reply
#8

Muy bueno men, asн la variedad de los scripters que no conocen el lenguage 'MySQL' al 100% puedan hacer algo aunque sea.
Reply
#9

Hola,

Muy buen aporte. їCrees que el include es sуlido? Es decir, puede tranquilamente usarse para cualquier proyecto que requiera MySQL. Respecto al plugin que suelen usar todos "oficial" cuбl serнa la principal ventaja y desventaja de cada uno. Se que arriba estбn pero bбsicamente es para diferenciar ambas.

Un saludo, gracias.
Reply
#10

Quote:
Originally Posted by Joake6
Посмотреть сообщение
Hola,

Muy buen aporte. їCrees que el include es sуlido? Es decir, puede tranquilamente usarse para cualquier proyecto que requiera MySQL. Respecto al plugin que suelen usar todos "oficial" cuбl serнa la principal ventaja y desventaja de cada uno. Se que arriba estбn pero bбsicamente es para diferenciar ambas.

Un saludo, gracias.

Osea, el include te facilita muchas cosas a la hora de hacer scripts con MySQL, supongo que puedes emplearlo para cualquier proyecto.

Respecto a tu pregunta, no la entiendo muy bien. Este include emplea el plugin que fue creado por BlueG y el link de la descarga se halla en la descripciуn.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)