日期:2014-05-16 浏览次数:20455 次
以前对数据库的操作基本上处于数据行阶段,在得知动态可以生成数据库表后很是激动,这可以更灵活的操作数据库,使用方法也出乎意料的简单,以C#为例:
string strSql = @"IF object_id('" + tableName + "') IS NULL Create Table " + tableName + "(QuestionId int IDENTITY(1,1)," + "ChapterId varchar(50) not null," + "QuestionTypeId varchar(50) not null," + "Point varchar(50) not null," + "Degree varchar(50) not null," + "Fraction float not null," + "QuestionContent text not null," + "Answer1 text," + "Answer2 text," + "Answer3 text," + "Answer4 text," + "CorrectAnswer text," + "IsValid varchar(10) constraint PK_" + tableName + " primary key (QuestionId))";
//创建一个数据库连接 sCmd = new SqlCommand(cmdText, sqlConn); //给该SqlCommand对象指定命令类型(执行的sql文本语句还是存储过程) sCmd.CommandType = cmdType; //该该SqlCommand对象增加参数 //sCmd.Parameters.AddRange(paras); //指定该Sqlcommand对象在事务中执行 sCmd.Transaction = sqlTran; //返回该命令执行后影响到的行数 return sCmd.ExecuteNonQuery();
原理很简单,就是首先判断要创建的表是否存在,如果不存在则创建;同时把创建表语句写到SQL语句中,再通过常用的SQL命名执行即可。
还是那句话,技术这东西不怕你学不会,就怕你不知道有这么个知识,即“不怕不知道,就怕不知道”。