调用类来进行数据库连接

Luk*_*uke 1 c# database ms-access class

我正在用C#编程.我正在尝试创建一个类,在调用时将创建与数据库的连接.

我的数据库连接类在这里:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace HouseServer
{

    class db
    {

        // Variable to hold the driver and location of database
        public static OleDbConnection dbConnection;

        // Database connection
        public db()
        {

            // Define the Access Database driver and the filename of the database
            dbConnection = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; Data Source=Houses.accdb");

            // Open the connection
            dbConnection.Open();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主程序在这里:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace HouseServer
{
    class Program : db
    {

        // List for holding loaded houses
        static List<house> houses = new List<house>();

        // Variable to hold "command" which is the query to be executed
        private static OleDbCommand query;

        // Variable to hold the data reader to manipulate data from the database
        static OleDbDataReader dataReader;

        static void Main(string[] args)
        {
            // Get the houses in a list
            List<house> c = getHousesFromDb();

            foreach (house yay in c)
            {
                // Show each house's full address
                Console.WriteLine(yay.house_number + " " + yay.street);
                Console.WriteLine(yay.house_town);
                Console.WriteLine(yay.postcode);
            }

            // Readline to prevent window from closing
            Console.ReadLine();
        }

        // Function which loads all of the houses from the database
        private static List<house> getHousesFromDb()
        {

            // Define the query to be executed
            query = new OleDbCommand("SELECT * FROM houses", dbConnection);

            // Execute the query on the database and get the data
            dataReader = query.ExecuteReader();

            // Loop through each of the houses
            while (dataReader.Read())
            {
                // Create a new house object for temporarily storing house
                house house = new house();

                // Create the house that we've just loaded
                house.house_id = Convert.ToInt32(dataReader["house_id"]);
                house.house_number = Convert.ToInt32(dataReader["house_number"]);
                house.street = dataReader["house_street"].ToString();
                house.house_town = dataReader["house_town"].ToString();
                house.postcode = dataReader["house_postcode"].ToString();

                // Now add the house to the list of houses
                houses.Add(house);
            }

            // Return all of the houses in the database as a List<house>
            return houses;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我认为put class Program : dbdb在程序打开时调用构造函数,但是当代码到达该行时dataReader = query.ExecuteReader();,它会出现错误"ExecuteReader:Connection属性尚未初始化.".

我想要实现的只是另一个类中的数据库连接,我可以调用它并且可用于我的所有代码.

我应该以不同的方式调用数据库类吗?

Jon*_*eet 13

不,没有什么是创建实例的Program,没有什么是创建实例的db.但是,我强烈建议您完全改变您的设计:

  • 没有用于数据库连接的静态字段.在需要时打开它,使用它,关闭它.您应该很少需要将其存储在除局部变量之外的任何其他内容中.
  • 如果可以帮助的话,尽量不要使用静态变量.它们使您的代码更难以测试,因为它们代表全局状态 - 这比本地状态更难以推理.在你的程序中,我完全使用局部变量.
  • 不要将继承用于此类事物 - 您的Program类型在逻辑上不是从中派生出来的db
  • 遵循方法,类和属性的.NET命名约定.让你的代码"感觉"像惯用语C#将有助于让其他人更具可读性.


Jon*_*onH 6

这肯定看起来不正确,您的程序不应继承或扩展您的数据库类.您的数据库类本身就是它自己的抽象数据类型.您的程序应该使用数据库类,但不能扩展它.

我会稍微改变一下

  1. 摆脱继承
  2. 使数据库类成为静态类(没有理由在此实例化数据库实例)
  3. 那么你的程序可以 DBClass.GetData();

那就是你的程序应该使用数据库类作为黑盒子,它绝对不应该继承它.它应该使用它而不具备它如何工作的细节.在你的代码中:

// List for holding loaded houses
static List<house> houses = new List<house>();

// Variable to hold "command" which is the query to be executed
private static OleDbCommand query;

// Variable to hold the data reader to manipulate data from the database
static OleDbDataReader dataReader;

static void Main(string[] args)
{
    // Get the houses in a list
    List<house> c = getHousesFromDb();
Run Code Online (Sandbox Code Playgroud)

您应该隐藏OleDbCommand和OleDbDatareader对象的详细信息,尽管不需要它们可以在其他地方进行管理.你getHousesFromDB应该被称为:

MyDBClass.GetHousesFromDB()

哪个MyDBClass是管理数据库读/写的静态类.签名GetHousesFromDB应该返回一些效果IList<House> GetHousesFromDB()