M2 Download Center
Download Here ( Internal )
You could use this code to create the relative functions in lua: mysql_direct_query, get_table_postfix, mysql_escape_string.
The mysql_direct_query returns two values: the first one contains the count of how many rows had been affected (works fine for select, insert, update queries, and so on) and the second one a table containing all the information retrieved by a select query (empty if not).
The field type will be auto-detected, which means:
A numeric field will be pushed as lua number
A BLOB one will be pushed as table byte per byte
A NULL field will be pushed as nil (not displayed in iteration)
The other ones will be pushed as strings (be aware of this)
Example
Example 1
Example 2
Example 3
How To
questlua_global.cpp
#include "db.h"
int _get_table_postfix(lua_State* L)
{
lua_pushstring(L, get_table_postfix());
return 1;
}
#ifdef _MSC_VER
#define INFINITY (DBL_MAX+DBL_MAX)
#define NAN (INFINITY-INFINITY)
#endif
int _mysql_direct_query(lua_State* L)
{
if (!lua_isstring(L, 1))
return 0;
int i=0, m=1;
MYSQL_ROW row;
MYSQL_FIELD * field;
MYSQL_RES * result;
std::auto_ptr<SQLMsg> pMsg(DBManager::instance().DirectQuery("%s", lua_tostring(L, 1)));
if (pMsg.get())
{
// ret1 (number of affected rows)
lua_pushnumber(L, pMsg->Get()->uiAffectedRows);
//-1 if error such as duplicate occurs (-2147483648 via lua)
// if wrong syntax error occurs (4294967295 via lua)
// ret2 (table of affected rows)
lua_newtable(L);
if ((result = pMsg->Get()->pSQLResult) &&
!(pMsg->Get()->uiAffectedRows == 0 || pMsg->Get()->uiAffectedRows == (uint32_t)-1))
{
while((row = mysql_fetch_row(result)))
{
lua_pushnumber(L, m);
lua_newtable(L);
while((field = mysql_fetch_field(result)))
{
lua_pushstring(L, field->name);
if (!(field->flags & NOT_NULL_FLAG) && (row[i]==NULL))
{
// lua_pushstring(L, "NULL");
lua_pushnil(L);
}
else if (IS_NUM(field->type))
{
double val = NAN;
lua_pushnumber(L, (sscanf(row[i],"%lf",&val)==1)?val:NAN);
}
else if (field->type == MYSQL_TYPE_BLOB)
{
lua_newtable(L);
for (DWORD iBlob=0; iBlob < field->max_length; iBlob++)
{
lua_pushnumber(L, row[i][iBlob]);
lua_rawseti(L, -2, iBlob+1);
}
}
else
lua_pushstring(L, row[i]);
lua_rawset(L, -3);
i++;
}
mysql_field_seek(result, 0);
i=0;
lua_rawset(L, -3);
m++;
}
}
}
else {lua_pushnumber(L, 0); lua_newtable(L);}
return 2;
}
int _mysql_escape_string(lua_State* L)
{
char szQuery[1024] = {0};
if (!lua_isstring(L, 1))
return 0;
DBManager::instance().EscapeString(szQuery, sizeof(szQuery), lua_tostring(L, 1), strlen(lua_tostring(L, 1)));
lua_pushstring(L, szQuery);
return 1;
}
{ "get_table_postfix", _get_table_postfix },
{ "mysql_direct_query", _mysql_direct_query },
{ "mysql_escape_string", _mysql_escape_string },
Author: Marty