当我通过UserExists
类实例调用DataBaseService
方法时,它立即失败以连接到数据库。尽管我已经为SqlConnection
提供了连接字符串,但实例为空。
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;
}
}
}
}
答案 0 :(得分:1)
您的代码DataBaseService
和_instance
中有两个Instance
个实例。您在静态构造函数中初始化_instance
,但从不初始化Instance
。
您可能希望在当前使用_instance
的任何地方使用Instance
,并完全摆脱Instance
:
...
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;
}
}
...
答案 1 :(得分:0)
您可能希望遵循以下模式:
private static DataBaseService _instance;
// public property
public static DataBaseService Instance
{
get
{
return _instance ?? (_instance = new DataBaseService());
}
}