using System;
using System.Data;
using System.Data.OleDb;

/*
SELECT QUERY
------------
string query = "SELECT * FROM [MyTable]";
DBConnect db = new DBConnect();
db.Connect();
DataTable dt = db.Select(query);
db.DisConnect();

OTROS QUERYS
------------
DBConnect db = new DBConnect();
db.Connect();
db.Script(query);
db.DisConnect();
*/

namespace Mercat_1.DBConnect
{
    public class DBConnect
    {
        OleDbConnection connection;
        OleDbCommand cmd;
        OleDbDataAdapter adapter;
        bool isset = false;

        public DBConnect()
        {
            connection = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "\\Mercatflor.accdb;Persist Security Info=True");
        }

        public string Script(string Query)
        {
            if (isset)
            {
                try
                {
                    cmd = new OleDbCommand(CheckInject(Query), connection);
                    object result = cmd.ExecuteScalar();
                    if (result == null)
                        return "1";
                    else
                        return result.ToString();
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
            return "0";
        }

        public DataTable Select(string Query)
        {
            if (isset)
            {
                DataTable dt = new DataTable();
                adapter = new OleDbDataAdapter(CheckInject(Query), connection);
                adapter.Fill(dt);
                return dt;
            }
            return new DataTable();
        }

         public void Connect()
        {
            if (!isset)
            {
                connection.Open();
                isset = true;
            }
        }

        public void DisConnect()
        {
            if (isset)
            {
                connection.Close();
                //connection = null;
                adapter = null;
                cmd = null;
                isset = false;
            }
        }

        public string CheckInject(string sql)
        {
            sql = sql.Replace("--", " ");
            sql = sql.Replace("/*", " ");
            //sql = sql.Replace('%', ' ');
            //sql.Replace('*', ' ');
            return sql;
        }

        public string CheckInjectText(string sql)
        {
            sql = sql.Replace(',', ' ');
            sql.Replace('$', ' ');
            sql.Replace('^', ' ');
            sql.Replace('%', ' ');
            return sql;
        }
    }
}
