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