私は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();
}
}
}
、メインプログラムはここにある:
私のデータベース接続クラスはここにある
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;
}
}
}
私はプログラムが開いたときにを置くことdb
コンストラクタを呼ぶだろうと思ったが、ときコードがdataReader = query.ExecuteReader();
行になると、 "ExecuteReader:Connectionプロパティが初期化されていません"というエラーが表示されます。
私が達成しようとしているすべては私が電話し、私のコードの全てに利用できる持っていることを、別のクラス内のデータベース接続です。
私は別の方法でデータベースクラスを呼び出すと思いますか?
アプリケーションを起動するクラスが必要です。この場合、プログラムであることを考慮すると、別のクラスを継承することはできません。作成したクラスを継承する理由はありません。 –
あなたのアドバイスのおかげで、私はそれを持ってそれから学ぶでしょう! – Luke