How to change database connection in run time?
Last modified:
To change database connection in runtime, you have to reload the Metadata Container, assign new database connection and/or new metadata and syntax providers (if you switch to another type of database server) on the server and refresh the Database Schema View on the client. It's as easy as follows. See the ChangeConnertion demo project for the details.
Client:
$.ajax({ type: 'POST', url: '/ChangeConnection/Change', data: { name: this.innerText }, success: function() { AQB.Web.QueryBuilder.fullUpdate(function() { $('.change').prop('disabled', false); }); }
Server:
public void ChangeConnection(string name) { var queryBuilder = QueryBuilderStore.Get(); queryBuilder.MetadataContainer.Clear(); if (name == "NorthwindXmlMetaData") SetNorthwindXml(queryBuilder); else if (name == "SQLite") SetSqLite(queryBuilder); else SetDb2Xml(queryBuilder); queryBuilder.MetadataStructure.Refresh(); } // Load metadata from XML file private void SetNorthwindXml(QueryBuilder qb) { qb.MetadataLoadingOptions.OfflineMode = true; qb.SyntaxProvider = new MSSQLSyntaxProvider(); // Load MetaData from XML document. // File name stored in WEB.CONFIG file in [/configuration/appSettings/Db2XmlMetaData] key. var path = ConfigurationManager.AppSettings["NorthwindXmlMetaData"]; var xml = Path.Combine(Server.MapPath("~"), path); qb.MetadataContainer.ImportFromXML(xml); } // Load metatafa from IBM DB2 connection private void SetDb2Xml(QueryBuilder qb) { qb.MetadataLoadingOptions.OfflineMode = true; qb.SyntaxProvider = new DB2SyntaxProvider(); // Load MetaData from XML document. File name stored in WEB.CONFIG file in [/configuration/appSettings/Db2XmlMetaData] key var path = ConfigurationManager.AppSettings["Db2XmlMetaData"]; var xml = Path.Combine(Server.MapPath("~"), path); qb.MetadataContainer.ImportFromXML(xml); } // Load metatafa from SQLite connection private void SetSqLite(QueryBuilder qb) { qb.MetadataLoadingOptions.OfflineMode = false; qb.SyntaxProvider = new SQLiteSyntaxProvider(); qb.MetadataProvider = new SQLiteMetadataProvider { Connection = DataBaseHelper.CreateSqLiteConnection("SqLiteDataBase") }; }
This sample has been taken from the Change Connection demo included in the trial installation package.