「S2Dao.NET」では、app.configにデータベースの接続情報を設定しますが、動的に変更したい場合があります。
今回は、app.configに設定したデータベースの接続情報を、プログラムで書き換える方法を説明します。
手順は以下の通り
- app.configの記述
- データベース接続情報を書き換える処理
1.app.configの記述
これは、通常の「S2Dao.NET」の記述方法と同じ。
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0"?> <configuration> <quill> <dataSources> <dataSource name="KTI_ETL_DB"> <provider>SqlServer</provider> <connectionString>"Server=SERVER01\SQLEXPRESS,1433;Database=KTI_ETL_DB;Trusted_Connection=Yes;"</connectionString> <class>Seasar.Extension.Tx.Impl.TxDataSource</class> </dataSource> </dataSources> </configuration> |
2.データベース接続情報を書き換える処理
app.configの設定情報を取得して、内容を書き換える
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/// <summary> /// Quillで管理しているSQL Serverのデータソースに引数のデータベース名を設定します /// </summary> /// <param name="dbname">データベース名</param> public static void SetDatabase(string dbname) { QuillInjector injector1 = QuillInjector.GetInstance(); var quill = injector1.Container.GetComponent(typeof(SelectableDataSourceProxyWithDictionary)); var dic = (SelectableDataSourceProxyWithDictionary)quill.GetComponentObject(typeof(SelectableDataSourceProxyWithDictionary)); var dataSource = (TxDataSource)dic.DataSourceCollection["KTI_ETL_DB"]; if (dataSource.ConnectionString.IndexOf(dbname) == -1) { string[] constrs = dataSource.ConnectionString.Split(';'); string[] database = constrs[1].Split('='); constrs[1] = string.Format("{0}={1}", database[0], dbname); dataSource.ConnectionString = string.Format("{0};{1};{2};", constrs); } } |