C# · 12月 28, 2021

C#创建数据库及导入sql脚本的方法

本文实例讲述了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#程序设计有所帮助。