gpt4 book ai didi

c# - 工厂模式数据库连接

转载 作者:可可西里 更新时间:2023-11-01 07:58:03 25 4
gpt4 key购买 nike

我正在尝试使用 MySQL 在数据库连接上实现工厂模式,SQL Server 遇到奇怪的错误

Object reference not set to an instance of an object

关于 SQL 命令对象

internal class SqlServerDB : IDatabase
{
private SqlConnection _Connection = null;
private SqlCommand _Command = null;

public IDbCommand Command
{
get
{
if (_Command == null)
{
_Command.Connection = (SqlConnection)Connection;

//_Command = new SqlCommand();
}
return _Command;
}
}

public IDbConnection Connection
{
get
{
if (_Connection == null)
{
string connectionString = ConfigurationManager.ConnectionStrings["testSQL"].ConnectionString;
_Connection = new SqlConnection(connectionString);
}
return _Connection;
}
}
}

数据库工厂部分:

public static class DatabaseFactory
{
public static IDatabase CreateDatabase(DBType type)
{
switch (type)
{
case DBType.SqlServer:
return new SqlServerDB();

case DBType.MySql:
return new MySQLDB();
}

return null;
}
}

主要方法

static void Main(string[] args)
{
IDatabase database;
DBType databaseType = DBType.SqlServer;

database = DatabaseFactory.CreateDatabase(databaseType);
IDbConnection connection = database.Connection;

IDbCommand command = database.Command;
command.CommandType = CommandType.Text;
command.CommandText = "select * from User";

connection.Open();
}

以及Enum对数据库的选择。

最佳答案

第一个if有错误,

if (_Command == null)
{
_Command.Connection = (SqlConnection)Connection;
//_Command = new SqlCommand();
}

可能更像:

if (_Command == null)
{
_Command = new SqlCommand();
_Command.Connection = (SqlConnection)Connection;
}

关于c# - 工厂模式数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com