To dynamically create a database, instead of designing a database in the SQL Enterprise ManagerProgramCreate a database and a table.
The concept of using a program to operate a database always begins with a connection to the database, and then commands are used to operate the database. But this time the problem is found, and there is no number I want to create
Who should I connect. Later we found that there is a database named master, which is the basis of the entire database system. First we can connect to it and then create our data
Database, and then change the current database connection. Use the newly created database for subsequent operations, such as table creation. Below is a section C #CodeTo display the information described above.
Note that we can put some SQL statements for table creation into a TXT document, set it as an embedded resource, and then read the SQL statement from the program.
Private string getsql (string name)
{
Try
{
// Gets the current Assembly.
Assembly ASM = assembly. getexecutingassembly ();
// Resources are named using a fully qualified name.
Stream STRM = ASM. getmanifestresourcestream (ASM. getname (). Name + "." + name );
// Reads the contents of the embedded file.
Streamreader reader = new streamreader (STRM );
Return reader. readtoend ();
}
Catch (exception ex)
{
Throw ex;
}
}
Private void executesql (string databasename, string SQL)
{
Sqlcommand command = new sqlcommand (SQL, this. sqlconnection1 );
Command. Connection. open ();
Command. Connection. changedatabase (databasename );
Try
{
Command. executenonquery ();
}
Finally
{
Command. Connection. Close ();
}
}
protected void adddbtable (string strdbname)
{< br> try
{< br> This. executesql ("master", "create database" + strdbname);
This. executesql (strdbname, this. getsql ("SQL .txt");
}< br> catch (exception ex)
{< br> throw ex;
}< BR >}