You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

177 lines
4.7 KiB

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MSSQL_MVVM_Sample.Structure;
namespace MSSQL_MVVM_Sample.Database
{
public sealed class SqlManager : Singleton<SqlManager>
{
public event ExceptionEventHandler ExceptionEvent;
public SqlConnection Connection { get; set; }
public string ConnectionString { get; set; }
private SqlCommand _lastExecutedCommand;
private int _retryCount;
public bool IsRunning { get { return CheckDBConnected(); } }
public static SqlManager GetNewInstanceConnection()
{
if (Instance == null)
return null;
SqlManager sqlManager = new SqlManager()
{
ConnectionString = Instance.ConnectionString
};
sqlManager.GetConnection();
sqlManager.ExceptionEvent = Instance.ExceptionEvent;
return sqlManager;
}
public void SetConnectionString(string connectionString)
{
ConnectionString = connectionString;
}
public bool GetConnection()
{
try
{
if (Connection != null)
{
Connection.Close();
Connection.Dispose();
Connection = null;
}
Connection = new SqlConnection(ConnectionString);
Connection.Open();
if (Connection.State != ConnectionState.Open)
return false;
return true;
}
catch (Exception ex)
{
HandleExceptionEvent("GetConnection", ex);
return false;
}
}
private bool CheckDBConnected()
{
try
{
string query = "SELECT GETDATE() Date";
SqlCommand cmd = new SqlCommand()
{
Connection = Connection,
CommandText = query,
};
SqlDataReader result = cmd.ExecuteReader();
if (result == null || !result.HasRows)
return false;
return true;
}
catch (Exception ex)
{
HandleExceptionEvent("CheckDBConnected", ex);
return false;
}
}
public int ExecuteNonQuery(string query)
{
try
{
lock (this)
{
SqlCommand cmd = new SqlCommand()
{
Connection = Connection,
CommandText = query,
};
return cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
HandleExceptionEvent("ExecuteNonQuery", ex);
return -1;
}
}
public int ExecuteNonQuery(string query, SqlParameter[] sqlParams)
{
try
{
lock (this)
{
SqlCommand cmd = new SqlCommand()
{
Connection = Connection,
CommandText = query,
};
for (int i = 0; i < sqlParams.Length; i++)
{
cmd.Parameters.Add(sqlParams);
}
return cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
HandleExceptionEvent("ExecuteNonQuery with sqlParams", ex);
return -1;
}
}
public DataSet ExecuteSelectQuery(string query)
{
try
{
lock (this)
{
SqlCommand cmd = new SqlCommand()
{
Connection = Connection,
CommandText = query,
};
SqlDataAdapter adt = new SqlDataAdapter()
{
SelectCommand = cmd,
};
DataSet ds = new DataSet();
adt.Fill(ds);
return ds;
}
}
catch (Exception ex)
{
HandleExceptionEvent("ExecuteNonQuery with sqlParams", ex);
return null;
}
}
private void HandleExceptionEvent(string id, Exception ex)
{
if (ExceptionEvent != null)
ExceptionEvent(id, ex);
}
}
}