usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls; Public Partial class_default:system.web.ui.page{protected voidPage_Load (Objectsender, EventArgs e) { } protected voidButton1_Click (Objectsender, EventArgs e) {Connectdb (); } Public voidConnectdb () {//Create a new connectionSqlConnection conn =NewSqlConnection (); //The connection string for the database master that already exists stringConntomaster ="Server=localhost;database=master; Uid=sa; pwd=123456"; //connection string for new database stringConntodb ="SERVER=LOCALHOST;DATABASE=SSPU; Uid=sa; pwd=123456"; //create the SQL statement for the database that will be executed by the existing database connection in the future//determine if the database and data tables exist stringCreatedbstr ="If not exists"+"("+"SELECT * from master.dbo.sysdatabases where name"+"= '"+"SSPU"+"')"+"Create Database [SSPU]"; stringCreatetablestr ="If not EXISTS (SELECT * from sysobjects where xtype= ' u ' and name= ' student ') CREATE TABLE student (s_id int primary key,n Ame Nchar (5))"; stringInsertstr ="INSERT into student values (1,n ' millet ')"; stringSelectstr ="SELECT * FROM Student"; //to create a new SqlCommand objectSqlCommand cmd =NewSqlCommand (CREATEDBSTR, conn); //first, connect to the database master that already exists,Conn. ConnectionString =Conntomaster; Conn. Open (); //executes the following statement, executes the SQL statement, which creates the databasecmd. ExecuteNonQuery (); //Conn. ChangeDatabase ("SSPU"); Conn. Close (); //Close old connection, open new connectionConn. ConnectionString =Conntodb; Conn. Open (); //int at = (int) cmd. ExecuteScalar (); Cmd.commandtext =Createtablestr; Cmd. ExecuteNonQuery (); Cmd.commandtext=Insertstr; Cmd. ExecuteNonQuery (); Conn. Close (); Cmd.commandtext=Selectstr; SqlDataAdapter da=NewSqlDataAdapter (CMD); DataTable DT=NewDataTable (); Da. Fill (DT); GridView GV=NewGridView (); Form1. Controls.Add (GV); Gv. AutoGenerateColumns=true; Gv. DataSource=DT; Gv. DataBind (); }}
Asp. NET dynamic creation of databases and tables