ASP.NET动态创建数据库和表

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ConnectDB();
    }

    public void ConnectDB()
        {
        //创建一个新连接 
        SqlConnection conn = new SqlConnection();
        //已经存在的数据库master的连接字符串 
        string connToMaster = "Server=localhost;DataBase=master;UID=sa;PWD=123456";
        //新建数据库的连接字符串 
        string connToDb = "Server=localhost;DataBase=SSPU;UID=sa;PWD=123456";
        //创建数据库的Sql语句,将来由已经存在的数据库连接执行此命令 
        //先判断数据库及数据表是否存在 
        string createDbStr = "if NOT exists"+
            "(" + "select * from master.dbo.sysdatabases where name " + "= '" + "SSPU" + "')" + "Create database [SSPU]";
        string createTableStr = "if not exists(select * from sysobjects where xtype='u' and name='student')create table student (s_id int primary key,name Nchar(5))";

        string insertStr = "insert into student values(1,N'小米')";
        string selectStr = "select * from student";
        //创建一个新的SqlCommand对象 
        SqlCommand cmd = new SqlCommand(createDbStr, conn);
       //首先连接到已经存在的数据库master, 
        conn.ConnectionString = connToMaster;
        conn.Open();
        //执行了下面的语句,就执行了SQL语句,即创建了数据库 
        cmd.ExecuteNonQuery();
        //conn.ChangeDatabase("SSPU"); 
        conn.Close();
        //关闭旧连接,打开新连接 
        conn.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 = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        GridView gv = new GridView();
        form1.Controls.Add(gv);
        gv.AutoGenerateColumns = true;
        gv.DataSource = dt;
        gv.DataBind();
        }

}

 

posted @ 2015-11-26 10:57  Wicrecend  阅读(2996)  评论(0编辑  收藏  举报
TOP