MySQL

From Pragma
Jump to: navigation, search

Name: wv_mysql

State:

SHARED

Description

By loading this module, the following classes are made available:

As well as the mysql library.

Examples

This example will build up a connection to a database, run a simple query and print the result in the console.
There are two ways of working with MySQL, synchronous or asynchronous. The synchronous calls will block the game until the operation is complete. Asynchronous calls will run in the background and call a callback once complete.

Synchronous:

local r = engine.load_library("mysql/wv_mysql")
if(r ~= true) then
	print("WARNING: An error occured trying to load the 'wv_mysql' module: ",r)
	return
end
local host = "tcp://127.0.0.1"
local user = "root"
local password = "yourpassword"
local database = "test"
local con = mysql.connect(host,user,password,database)
if(con == nil) then
	print("Unable to connect to database '" .. database .. "' on host '" .. host .. "': " .. mysql.get_error())
	return
end
local statement = con:CreateStatement()
if(statement ~= nil) then
	local result = statement:ExecuteQuery("SELECT 'Hello World!' AS _message;")
	if(result ~= nil) then
		while(result:FetchNext() == true) do
			print("Value: ",result:GetString("_message")) -- Alternative: result:GetString(1) (Grab the value from column 1)
		end
		result:Release()
	else print("Unable to execute query: " .. mysql.get_error()) end
	statement:Release()
else print("Unable to create statement: " .. mysql.get_error()) end
con:Release() -- Always make sure to release all MySQL objects, or you'll end up with memory leaks!


Asynchronous:

local r = engine.load_library("mysql/wv_mysql")
if(r ~= true) then
	print("WARNING: An error occured trying to load the 'wv_mysql' module: ",r)
	return
end
local host = "tcp://127.0.0.1"
local user = "root"
local password = "yourpassword"
local database = "test"
mysql.connect(host,user,password,database,function(con)
	if(con == nil) then
		print("Unable to connect to database '" .. database .. "' on host '" .. host .. "': " .. mysql.get_error())
		return
	end
	local statement = con:CreateStatement()
	if(statement ~= nil) then
		statement:ExecuteQuery("SELECT 'Hello World!' AS _message;",function(result)
			if(result ~= nil) then
				while(result:FetchNext() == true) do
					print("Value: ",result:GetString("_message")) -- Alternative: result:GetString(1) (Grab the value from column 1)
				end
				result:Release()
			else print("Unable to execute query: " .. mysql.get_error()) end
			statement:Release()
			con:Release()
		end)
	else con:Release(); print("Unable to create statement: " .. mysql.get_error()) end
end)

See Also