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

时间:2021-05-20

复制代码 代码如下:
//必须的命名空间
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();

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章