欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-15 09:05:22
复制代码 代码如下://必须的命名空间using system;using system.data;using system.data.sqlclient;//中间常规内容...

复制代码 代码如下:

//必须的命名空间
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();

上一篇:

下一篇: