Reputation: 1
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;
}
}
}
}
Upvotes: 0
Views: 965
Reputation: 10247
You might want to follow this pattern:
private static DataBaseService _instance;
// public property
public static DataBaseService Instance
{
get
{
return _instance ?? (_instance = new DataBaseService());
}
}
Upvotes: 0
Reputation: 3785
You have two instances of DataBaseService
in your code, _instance
and Instance
. You initialize _instance
in the static constructor, but never initialize Instance
.
You probably want to use _instance
everywhere you're currently using Instance
, and get rid of Instance
entirely:
...
private static readonly DataBaseService _instance;
static DataBaseService()
{
_instance = new DataBaseService();
Initilize();
}
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;
}
}
...
Upvotes: 1