我正在尝试使用MySQL在SQL Server上实现工厂模式,SQL Server面临奇怪的错误
对象引用未设置为对象的实例
在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选择数据库。
答案 0 :(得分:5)
第一个if上有错误,
if (_Command == null)
{
_Command.Connection = (SqlConnection)Connection;
//_Command = new SqlCommand();
}
可能更像是:
if (_Command == null)
{
_Command = new SqlCommand();
_Command.Connection = (SqlConnection)Connection;
}
答案 1 :(得分:0)
您不必使用自己的switch语句。
首先,确保您的connectionString包含这样的providerName:
< ?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionstrings>
<add name="Name" providerName="System.Data.ProviderName" connectionString="Valid Connection String;"></add>
</connectionstrings>
</configuration>
然后您可以使用以下方式创建连接:
var connectionString = ConfigurationManager.ConnectionStrings["MyConName"];
var providerName = connectionString.ProviderName;
var factory = DbProviderFactories.GetFactory(providerName);
var connection = factory.CreateConnection();
connection.ConnectionString = connectionString.ConnectionString;
connection.Open();
(添加空检查,以便您可以告诉您的用户/开发人员配置错误)
只要您坚持常见的SQL查询,就可以支持大多数SQL数据库。
想要了解有关正确ADO.NET处理的更多信息? http://blog.gauffin.org/2013/01/ado-net-the-right-way/