I'm in the process of learning SQLite in C# and I've come up with some generic methods for finding and updating data. I would appreciate any pointers with the design of my methods and/or my SQL syntax.
FYI: I'm using System.Data
and Mono.Data.SqliteClient
for C# Mono 2.0 (Unity3D).
Here is an example of the database used for this post. Let's also assume that I check for null prior to obtaining/updating data.
Info - Table name
| display_name | coins | total_score |
| Michael | 100 | 1356 |
| John | 50 | 904 |
Below is my FindData
method, which is used to lookup data in a specified table.
public object FindData (string tableName, string selectHeader, string whereHeader, object whereValue)
{
using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
{
dbConnection.Open ();
using (var dbCommand = dbConnection.CreateCommand ())
{
dbCommand.CommandText = string.Format ("SELECT {0} " +
"FROM {1} " +
"WHERE {2} = @whereValue", selectHeader, tableName, whereHeader);
SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);
dbCommand.Parameters.Add (whereParam);
using (var dbReader = dbCommand.ExecuteReader ())
{
while (dbReader.Read ())
{
if (dbReader.GetValue (0) != null)
return dbReader.GetValue (0);
}
}
}
}
return null;
}
I attempted to have SQL Injection prevention parameters for tableName
, selectHeader
and whereHeader
, however, it kept throwing an error saying the syntax was wrong. I'm assuming this can't be done then.
That method can be used like so:
int coins = (int)FindData ("Info", "coins", "display_name", "Michael");
This attempts to obtain the value under column coins
, from the table Info
where the display_name
column is equal to Michael
Next I have the UpdateData
method. This is used to update/save the data in the specified table.
public void UpdateData (string tableName, string whereHeader, object whereValue, string setHeader, object setValue)
{
using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
{
dbConnection.Open ();
using (var dbCommand = dbConnection.CreateCommand ())
{
dbCommand.CommandText = string.Format ("UPDATE {0} " +
"SET {1} = @setValue " +
"WHERE {2} = @whereValue",
tableName, setHeader, whereHeader);
SqliteParameter setParam = new SqliteParameter ("@setValue", setValue);
SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);
dbCommand.Parameters.Add (setParam);
dbCommand.Parameters.Add (whereParam);
Debug.Log (dbCommand.CommandText);
dbCommand.ExecuteNonQuery ();
}
}
}
This method can be used like so:
UpdateData ("Info", "display_name", character.displayName, "coins", character.coins);
This method attempts to update the Info
table, based on the column displayName
, which equals character.displayName
, which then updates the coins
column based on the character.coins
variable
Can anyone provide any criticism/advice on these generic methods for saving and loading data from a Sqlite database.