When I call the UserExists
method via the DataBaseService
class instance it fails immediately to connect to database. Instance is null despite the fact that I have provided the SqlConnection
with a connection string.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Somename
{
public class DataBaseService
{
// Setting up the Database Services
private SqlConnection myConnection;
private const string ConnectionString = "Data Source=Test-LAPTOP\\MSSQLSERVER1;Initial Catalog=myDatabaseTest;Integrated Security=True";
private static readonly DataBaseService _instance;
static DataBaseService()
{
_instance = new DataBaseService();
Initilize();
}
public static DataBaseService Instance;
private static void Initilize()
{
try
{
Instance.myConnection = new SqlConnection(ConnectionString);
Instance.myConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show("Error while connecting to DB: " + ex.Message);
return;
}
}
public bool UserExists(string username)
{
var myQuery = "Select * from UserProfile where userId ="+username+"";
SqlCommand sqlCmd = new SqlCommand(myQuery, Instance.myConnection);
sqlCmd.CommandType = CommandType.Text;
//sqlCmd.CommandText = "Select * from Customers";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
if (dtRecord == null)
{
return false;
}
else
{
return true;
}
}
}
}