Run SQL Statements - nabrezzelt/HelperLibrary GitHub Wiki
Introdution
In the HelperLibrary the queries are splitted in 2 sections.
- Select-Statements means statements with return value(s) and
- Insert-, Update- or Delete-Statments with no return (excluding the last insert ID)
In general you need a connected instance of MySQLDatabaseManager
(if you don't know how this works, it's here explaied).
Select statements
Select statments can be run with the Select(query);
method. The method returns a reader of type MySqlDataReader
. The reading is quite easy - just call reader.Read()
in a while loop if you expect multiple rows or without a while loop if you expect only one row as result. Inside the loop you can access the data with reader.GetInt32()
if the column type is a int or reader.GetString()
if the column type is a string.
To tell the GetValue()
method witch column you want you can pass the columnname or the columnindex as argument.
Example
Your database structure for the table users is as follows:
id | username | password | banned |
---|---|---|---|
int | varchar | varchar | tinyint |
To get the user with a specific id you can use this code example:
var userId = 1;
var query = "SELECT * FROM users WHERE id = " + userId;
var reader = _dbManagerDefault.Select(query);
reader.Read();
var id = reader.GetInt32(0);
var username = reader.GetString(1);
var password = reader.GetString(2);
var banned = reader.GetBoolean(3);
reader.Close();
var user = new User(id, username, password, banned);
It's important to close the reader with reader.Close()
after reading the records.