C# asp .net 在sql数据库中动态插入列、删除列

c# asp .net 在sql数据库中动态插入列、删除列:

//必须的命名空间
using System;
using System.Data;
using System.Data.SqlClient;

//插入列

string tabName = "table1"; //欲插入列的表名
string colName = "col6"; //插入列的列名
string sqlStr = "alter table " + tabName + " add " + colName + " varchar(10) null";

//实例化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 = "table1"; //欲删除列的表名
string colName = "col6"; //删除列的列名
string sqlStr = "alter table " + tabName + " drop column " + colName;

//实例化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();
发表评论 / Comment

用心评论~