// Kelsier project - Database interaction code (Database.cs)
// Written by the Jobbig codeteam.
// Copyright 2013 John Runyon.
//
// This file is part of the Kelsier project.
//
// Kelsier is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace Kelsier.Common {
public class Database {
public MySqlConnection dbh { get; private set; }
private string dbinfo;
///
/// Construct a Database, using the MySQL connector string.
///
/// Connector string
public Database(string dbinfo) {
this.dbinfo = dbinfo;
dbh = new MySqlConnection(this.dbinfo);
dbh.Open();
}
public Database(Database copy) {
this.dbinfo = copy.dbinfo;
dbh = new MySqlConnection(this.dbinfo);
dbh.Open();
}
~Database() {
dbh.Close();
}
public int execute(string query) {
MySqlCommand cmdo = new MySqlCommand(query, dbh);
return cmdo.ExecuteNonQuery();
}
public int execute(string query, object[] keys) {
MySqlCommand cmdo = new MySqlCommand();
cmdo.Connection = dbh;
cmdo.CommandText = query;
cmdo.Prepare();
for (int i = 0; i < keys.Length; i += 2) {
cmdo.Parameters.AddWithValue(keys[i].ToString(), keys[i + 1]);
}
return cmdo.ExecuteNonQuery();
}
public object queryScalar(string query) {
MySqlCommand cmdo = new MySqlCommand(query, dbh);
return cmdo.ExecuteScalar();
}
public object queryScalar(string query, object[] keys) {
MySqlCommand cmdo = new MySqlCommand();
cmdo.Connection = dbh;
cmdo.CommandText = query;
cmdo.Prepare();
for (int i = 0; i < keys.Length; i += 2) {
cmdo.Parameters.AddWithValue(keys[i].ToString(), keys[i + 1]);
}
return cmdo.ExecuteScalar();
}
public MySqlDataReader queryReader(string query) {
MySqlCommand cmdo = new MySqlCommand(query, dbh);
return cmdo.ExecuteReader();
}
public MySqlDataReader queryReader(string query, object[] keys) {
if (keys.Length % 2 != 0) {
throw new PlaceholdersException();
}
MySqlCommand cmdo = new MySqlCommand();
cmdo.Connection = dbh;
cmdo.CommandText = query;
cmdo.Prepare();
for (int i = 0; i < keys.Length; i += 2) {
cmdo.Parameters.AddWithValue(keys[i].ToString(), keys[i + 1]);
}
return cmdo.ExecuteReader();
}
}
public class PlaceholdersException : Exception { }
}