动态创建sql数据库表 c# asp .net 动态创建sql数据库表的方法
人气:0想了解c# asp .net 动态创建sql数据库表的方法的相关内容吗,在本文为您仔细讲解动态创建sql数据库表的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:动态,创建,表,下面大家一起来学习吧。
复制代码 代码如下:
//必须的命名空间
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();
加载全部内容