简体   繁体   中英

Null reference exception when connecting to a database

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;
            }
        }
    }
}

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;
    }
}

...

You might want to follow this pattern:

private static DataBaseService _instance;
// public property
public static DataBaseService Instance
{
    get
    {
        return _instance ?? (_instance = new DataBaseService());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM