2017-05-29 62 views
2

我试图使用MySQL,SQL服务器面临着奇怪的错误没有设置对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(); 
} 

和数据库的由枚举选择。

回答

5

有第一如果有错误,

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

可能是更喜欢:

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

完美的男人谢谢你! –

0

你不必使用自己的switch语句。

首先,请确保您的connectionString包含像这样的的providerName:

​​

,那么你可以通过创建连接:

var connectionString = ConfigurationManager.ConnectionStrings["MyConName"]; 
var providerName = connectionString.ProviderName; 
var factory = DbProviderFactories.GetFactory(providerName); 
var connection = factory.CreateConnection(); 
connection.ConnectionString = connectionString.ConnectionString; 
connection.Open(); 

(添加null检查,以便您可以告诉你的用户/开发者配置是错误的)

那样你可以支持大多数SQL数据库lon g,因为你坚持常见的SQL查询。

想了解更多关于正确的ADO.NET处理? http://blog.gauffin.org/2013/01/ado-net-the-right-way/