2017-05-29 63 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/