C # resolves dynamic creation of libraries, dynamic creation of tables

Source: Internet
Author: User
Tags connectionstrings

in the One Month Ten number. We started to do the university platform this project, the project, there are many subsystems. Authority system, basic system, examination system ...

since it is a university platform, of course, not only a school, can be a lot of school public. That being the case, it is certainly not possible for each school to store the data in a library. A school a library, then how many schools use it? Unknown. The number of libraries is subject to availability. Creating a library dynamically solves this problem.

of course, there are many systems. But individuals are only involved in the development of subsystems. have been in the test system in the past to do chores. After the project was allocated, I began to shading a way to do the chores .

in the process of doing the project, the assignment of the task is very clear. What time to do what things, daily tasks and so on. Coupled with the division of the module, the coupling between the systems to the low principle. This requires that the underlying stuff be encapsulated in a particularly good, reusable high.

Because it has been a number of questions and the question Bank of the modules. This is more abstract than the other modules. Because each question question has the different characteristic. The way you need to save is different. As for the question bank, it is necessary to provide support.

You can't write every question. That's not exhausting.

When it comes to demand, you already know that this part of the question is alive. This requires a new approach-creating tables dynamically.

Dynamically generate the library, generating the table. Only know that using these can solve the above problems.

in the absence of contact with these things, the prototype of the painting question ... Can't draw. The class diagram of the drawing questions ... Draw out every question? Tired not to say, still can't expand.

the system to do so, to add questions, change the code that is certain.

It happened that a while ago was called up by the leader, the task to be done, is also very suitable. is to encapsulate the method of creating the database and the method of creating the database table.

It is very useful to understand the needs of the question.

the task is very vague, first make a Demo , can be achieved on the line.

1 , provide the database name, and then go to create.

2 , specify the database and data tables. Of course, table fields and data types must also be provided . To create a table.

After studying a few, we'll use stitching first. SQL statement method to do it. Please note that there are other ways.

These things are encapsulated at the bottom. Therefore , the method of dynamically creating the library needs to use the SqlHelper. It's not written here. If necessary, there are at the end of the article.

 #region determine if the database exists///<summary>//Determine if the database exists///</summary>//<param name= " DB > Database name </param>//<param name= "Connkey" > Database connection key</param>//<returns>true: Indicates that the database already exists; False, indicating that the database does not exist </returns> public Boolean isdbexist (string db,string connkey) {SQL            Helper helper = Sqlhelper.getinstance (); String conntomaster = Configurationmanager.connectionstrings[connkey].            ToString ();            String createdbstr = "SELECT * from master.dbo.sysdatabases where name" + "= '" + db + "'"; DataTable dt= Helper.            ExecuteQuery (Createdbstr, CommandType.Text); if (dt.            Rows.count==0) {return false;            } else {return true; }} #endregion #region to determine whether the table exists in the database,///<summary>///To determine if the database table exists///&L t;/summary>//<param name= "db" > Database </param>//<param name= "TB" > Data table name </param>///<param Name= "Connkey" > Number of connections key</param>//<returns>true: Indicates that the data table already exists; false, indicating that the data table does not exist </returns> public Boolean istable            Exist (String db,string TB, string connkey) {SQLHelper helper = sqlhelper.getinstance (); String conntomaster = Configurationmanager.connectionstrings[connkey].            ToString ();            String createdbstr = "Use" + DB + "Select 1 from sysobjects where id = object_id ('" + TB + "') and type = ' U '"; Finds the table in the specified database if there is a DataTable dt = helper.            ExecuteQuery (Createdbstr, CommandType.Text); if (dt.            Rows.Count = = 0) {return false;            } else {return true;         }} #endregion #region CREATE DATABASE///<summary>//CREATE DATABASE///</summary> <param name= "db" > DatabaseName </param>//<param name= "Connkey" > Connection database key</param> public void CreateDatabase (string d            b, String connkey) {SQLHelper helper = sqlhelper.getinstance ();            A symbolic variable that determines whether the database exists with Boolean flag = isdbexist (db, Connkey); If the database exists, throw if (flag = = True) {throw new Exception ("The database already exists!")            "); } else {//database does not exist, create database string conntomaster = Configurationmanager.con Nectionstrings[connkey].                ToString ();                String createdbstr = "Create database" + db; Helper.            ExecuteNonQuery (Createdbstr, CommandType.Text); #endregion #region Create a database table///<summary>///In the specified database, create a data table///</         summary>//<param name= "DB" > specified database </param>///<param name= "DT" > data table to be created </param> <param name= "dic" > fields and their data in the data sheetType </param>//<param name= "Connkey" > Database connection key</param> public void createdatatable (string DB, String dt, dictionary<string, string> dic, String connkey) {SQLHelper helper = Sqlhelper.geti            Nstance (); String conntomaster = Configurationmanager.connectionstrings[connkey].            ToString (); Determine if the database exists if (isdbexist (db, connkey) = = False) {throw new Exception ("Database does not exist!            "); }//If the database table exists, then throws an error if (istableexist (db, dt, connkey) = = True) {throw new Exception ("database table already exists!            "); } else//data table does not exist, create data table {//stitching string, (the string to create content) string content = "Serial int"                Identity (primary) key "; Take out the contents of DIC and make stitching list<string> test = new List<string> (dic.                Keys); for (int i = 0; i < dic. Count (); i++) {conTent = content + "," + test[i] + "" + dic[test[i]];  }//Then determine if the data table exists and then create the data table string createtablestr = "Use" + DB + "CREATE TABLE" + dt + "(" +                Content + ")"; Helper.            ExecuteNonQuery (Createtablestr, CommandType.Text); }} #endregion


The above is a function that creates a table related to the dynamic creation of the library.

Here is the call

protected void Page_Load (object sender, EventArgs e)        {            if (! Page.IsPostBack)            {                //create a library named Testquestion                createdatabase ("Questiontype", "MSSql2012");                Use a Dictionary type to save the field and data type of the database table                dictionary<string, string> dic = new dictionary<string, string> ();                DiC. ADD ("Questionname", "varchar");                Dic. ADD ("content", "varchar");                Create a table named Xuanzeti in the Questiontype library                createdatatable ("Questiontype", "Xuanzeti", DIC, "MSSql2012");            }        


Here are the effects before and after execution:

with Stitching SQL the way the statements are encapsulated is very easy to understand. As the underlying thing, reusability is very high. So this piece is also the first edition.

If there is a better way, please contact me.

demo:http://download.csdn.net/detail/zc474235918/8207857

C # resolves dynamic creation of libraries, dynamic creation of tables

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.