Reputation: 93
i want to create a class that handles all my Database-Stuff so i started with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace Server
{
class Database
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Database()
{
server = "localhost";
database = "mydb";
uid = "root";
password = string.Empty;
string connectionString = "SERVER=" + server + ";" + "DATABASE = " + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
connection.Open();
return true;
} catch(MySqlException e)
{
switch (e.Number)
{
case 0:
// Cannot connect to server
break;
case 1045:
// Invalid username / password
break;
}
return false;
}
}
private bool CloseConnection()
{
try
{
connection.Close();
return true;
} catch(MySqlException e)
{
// ex.message
return false;
}
}
}
}
But i don't know how i should handle inserts, updates and selects that they are dynamic to usw. I want to insert strings, dates and integers.. what is the best solution to create an insert, update and select function that can be used from everywhere?
Upvotes: 0
Views: 6094
Reputation: 514
You have two options.
A) Make methods for every possible Select/Insert/Update/Delete within the Database class
or
B) Make a generic Select and Insert/Update/Delete method which takes an sql query (string) and array/list of SqlParameter and then this data is passed to the functions from another class
The Select method should return a DataTable and the Insert/Update/Delete method could return a value to determine success
Personally I much prefer option B.
Upvotes: 1