简体   繁体   中英

Why Am I getting this error in C# class?

Before anyone votes my question down, I would like to say that this is my first time using classes in C# and I have done a lot of research but I am still encountering errors. Newbie here.

I am trying to put the Insert, Delete, Update, and Count statements in a class file so that my code will be neat.

Here is the class file I made (with the help of research of course):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Windows.Forms;

namespace classlib
{
public class DBConnect
{
    private static MySqlConnection mycon;
    private string server;
    private string database;
    private string uid;
    private string password;

    public DBConnect()
    {
        Initialize();
    }

    private void Initialize()
    {
        server = "localhost";
        database = "restaurantdb";
        uid = "user";
        password = "root";
        string connectionString;
        connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
        mycon = new MySqlConnection(connectionString);
    }

    private static bool OpenConnection()
    {
        try
        {
                mycon.Open();
            return true;
        }
        catch (MySqlException ex)
        {
            switch (ex.Number)
            {
                case 0:
                    MessageBox.Show("Cannot connect to server.  Contact administrator");
                    break;

                case 1045:
                    MessageBox.Show("Invalid username/password, please try again");
                    break;
            }
            return false;
        }
    }

    private static bool CloseConnnection()
    {
        try
        {
            mycon.Close();
            return true;
        }

        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
            return false;
        }
    }


    public static void Insert(string query)
    {
        if (OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, mycon);
            cmd.ExecuteNonQuery();
            CloseConnnection();
        }
    }

    public static void Update(string query)
    {
        if (OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = query;
            cmd.Connection = mycon;

            cmd.ExecuteNonQuery();
            CloseConnnection();
        }
    }

    public static void Delete(string query)
    {
        if (OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, mycon);
            cmd.ExecuteNonQuery();
            CloseConnnection();
        }
    }

    public static int Count(string query)
    {
        int count = -1;

        if (OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, mycon);

            count = int.Parse(cmd.ExecuteScalar() + "");

            CloseConnnection();

            return count;
        }

        else
        {
            return count;
        }
    }

}
}

I was just trying the Count Method like in a certain form. Here is my code:

        MessageBox.Show("NUMBER OF ACCOUNTS IN DATABASE = "+ DBConnect.Count("SELECT count(*) FROM usersettingsdb") +"", "CONFIRMATION");

But I get this error on the class file on the OpenConnection() method on the mycon.Open() line:

Object reference not set to an instance of an object.

How do I remove the said error and access the methods through calling it like so DBConnect.MethodName() ?

I don't quite get anything about classes but I would really like to know how I can create my own functions/methods so as to keep my code neat.

Ok this is because you are messing up thing using in some cases static fields and in other cases not. There are tons of paper about static classes/members, see here for example.

The initialization code won't be called if you use the class as you are using.

In your case you should have a DBConnect instance and remove the static from methods

var db = new DBConnect();

and then use that in order to make queries:

db.Count(...);

Another solution is to call the Initialize method inside the Count method. You should modify Initialize in order to make it static (you will have to make all of your fields as static )

Another users will answer this question propably. So I want to mention different things. Your code is not very good. Instead of using it ,you can take a look at use of repository pattern. You can also use petapoco for database. These facilitate your work.

http://www.remondo.net/repository-pattern-example-csharp/

http://www.toptensoftware.com/petapoco/

Your myCon object is initialized in the Initialize() method, which is called in the constructor of the class, so only when you create an instance of DbConnect .

mycon = new MySqlConnection(connectionString);

In your code, you have no instance of DbConnect , you just call the static method Count of the class. So, the myCon is null .

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