码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2015-11-26 12:23:48      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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();
        }

}

 

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

标签:

原文地址:http://www.cnblogs.com/wicrecend/p/4997020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!