c# asp .net 动态创建sql数据库表

作者:互联网   出处:控件中国网   2014-11-05 19:05:51   阅读:1

c# asp .net 动态创建sql数据库表
 
//必须的命名空间
using System;
using System.Data;
using System.Data.SqlClient;
//中间常规内容略
string tabName = "table1";
//声明要创建的表名,你也可以改为从textbox中获取;
string sqlStr = "create table ";
sqlStr += tabName + "( ";
sqlStr += "col0 numeric identity(1,1) primary key,";
//col0为列名,同样可以改为通过从textbox中获取
//identity(1,1)是标记递增种子
//primary key定义主键
sqlStr += "col1 varchar(20),";
sqlStr += "col2 smalldatetime,";
sqlStr += "col3 varchar(20),";
sqlStr += "col4 int,";
sqlStr += "col5 varchar(20),";
sqlStr += " )";

//实例化sql连接
SqlConnection conn = new SqlConnection("server=.; database=dbName; uid=sa; pwd=sa");
conn.Open();
//实例化sql命令
SqlCommand cmd = new SqlCommand(sqlStr, conn);
//执行sql命令
cmd.ExecuteNonQuery();
//关闭连接
conn.Close();

我的代码:

       string tabName = "Job";
        string sqlStr = "create table ";
        sqlStr += tabName + "( ";
        sqlStr += "Id int identity(1,1) primary key,";
        //col0为列名,同样可以改为通过从textbox中获取
        //identity(1,1)是标记递增种子
        //primary key定义主键

       sqlStr += "num int,";
        sqlStr += "Colour varchar(50),";

       sqlStr += "Other varchar(50),";
        sqlStr += " )";

       //实例化sql连接
        string sss = "Data Source=(local);Initial Catalog=" + dataconnect + ";Integrated Security=True";
        SqlConnection conn = new SqlConnection(sss );
        conn.Open();

       //实例化sql命令
        SqlCommand cmd = new SqlCommand(sqlStr, conn);

       //执行sql命令
        cmd.ExecuteNonQuery();

       //关闭连接
        conn.Close();

 

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat