C#创建数据库及导入sql脚本的方法
程序员文章站
2024-01-02 16:30:52
本文实例讲述了c#创建数据库及导入sql脚本的方法。分享给大家供大家参考,具体如下:
c#创建数据库:
///
/// 创建数...
本文实例讲述了c#创建数据库及导入sql脚本的方法。分享给大家供大家参考,具体如下:
c#创建数据库:
/// <summary> /// 创建数据库 /// </summary> /// <param name="connstr">连接字符串</param> /// <param name="_strdbname">数据库名称</param> /// <returns></returns> private static bool createdatabase(string connstr, string _strdbname) { bool bsuccess = false; try { using (sqlconnection conmaster = new sqlconnection(connstr)) { conmaster.open(); // check if the database has existed first string strexist = @"select * from dbo.sysdatabases where name='" + _strdbname + @"'"; sqlcommand cmdexist = new sqlcommand(strexist, conmaster); sqldatareader readerexist = cmdexist.executereader(); bool bexist = readerexist.hasrows; readerexist.close(); if (bexist) { string strdel = @"drop database " + _strdbname; sqlcommand cmddel = new sqlcommand(strdel, conmaster); cmddel.executenonquery(); } // create the database now; string strdatabase = "create database [" + _strdbname + "]"; sqlcommand cmdcreate = new sqlcommand(strdatabase, conmaster); cmdcreate.executenonquery(); conmaster.close(); } bsuccess = true; } catch (exception e) { throw e; } return bsuccess; }
c#导入sql脚本:
/// <summary> /// 导入sql脚本 /// </summary> /// <param name="sqlconnstring">连接数据库字符串</param> /// <param name="varfilename">脚本路径</param> /// <returns></returns> private static bool executesqlfile(string sqlconnstring, string varfilename) { if (!file.exists(varfilename)) { return false; } streamreader rs = new streamreader(varfilename, system.text.encoding.default); arraylist alsql = new arraylist(); string commandtext = ""; string varline = ""; while (rs.peek() > -1) { varline = rs.readline(); if (varline == "") { continue; } if (varline != "go") { commandtext += varline; commandtext += "\r\n"; } else { commandtext += ""; } } alsql.add(commandtext); rs.close(); try { executecommand(sqlconnstring, alsql); return true; } catch (exception ex) { throw ex; } } private static void executecommand(string sqlconnstring, arraylist varsqllist) { using (sqlconnection conn = new sqlconnection(sqlconnstring)) { conn.open(); //don't use transaction, because some commands cannot execute in one transaction. //sqltransaction vartrans = conn.begintransaction(); sqlcommand command = new sqlcommand(); command.connection = conn; //command.transaction = vartrans; try { foreach (string varcommandtext in varsqllist) { command.commandtext = varcommandtext; command.executenonquery(); } //vartrans.commit(); } catch (exception ex) { //vartrans.rollback(); throw ex; } finally { conn.close(); } } }
希望本文所述对大家c#程序设计有所帮助。
推荐阅读
-
C#创建数据库及导入sql脚本的方法
-
PHP将Excel导入数据库及数据库数据导出至Excel的方法,excel数据导出_PHP教程
-
sql脚本查询数据库表,数据,结构,约束等操作的方法
-
SQL Server的数据导入MySQL数据库方法简介(1)
-
MySQL从命令行导入SQL脚本时出现中文乱码的解决方法
-
c# asp .net 动态创建sql数据库表的方法
-
Windows 8 Metro用C#连接SQLite及创建数据库,数据表的增删改查的实现
-
C#实现连接SQL Server2012数据库并执行SQL语句的方法
-
Laravel5.1数据库连接、创建数据库、创建model及创建控制器的方法
-
C#、vb.net及SQL判断指定年份是否为闰年的方法