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脚本方式,代码如下:
1 /// <summary> 2 /// 导入sql脚本 3 /// </summary> 4 /// <param name="sqlConnString">连接数据库字符串</param> 5 /// <param name="varFileName">脚本路径</param> 6 /// <returns></returns> 7 private static bool ExecuteSqlFile(string sqlConnString, string varFileName) 8 { 9 if (!File.Exists(varFileName)) 10 { 11 return false; 12 } 13 StreamReader rs = new StreamReader(varFileName, System.Text.Encoding.Default); 14 ArrayList alSql = new ArrayList(); 15 string commandText = ""; 16 string varLine = ""; 17 while (rs.Peek() > -1) 18 { 19 varLine = rs.ReadLine(); 20 if (varLine == "") 21 { 22 continue; 23 } 24 if (varLine != "GO") 25 { 26 commandText += varLine; 27 commandText += "\r\n"; 28 } 29 else 30 { 31 commandText += ""; 32 } 33 } 34 alSql.Add(commandText); 35 rs.Close(); 36 try 37 { 38 ExecuteCommand(sqlConnString, alSql); 39 return true; 40 } 41 catch (Exception ex) 42 { 43 throw ex; 44 } 45 } 46 private static void ExecuteCommand(string sqlConnString, ArrayList varSqlList) 47 { 48 using (SqlConnection conn = new SqlConnection(sqlConnString)) 49 { 50 conn.Open(); 51 //Don't use Transaction, because some commands cannot execute in one Transaction. 52 //SqlTransaction varTrans = conn.BeginTransaction(); 53 SqlCommand command = new SqlCommand(); 54 command.Connection = conn; 55 //command.Transaction = varTrans; 56 try 57 { 58 foreach (string varcommandText in varSqlList) 59 { 60 command.CommandText = varcommandText; 61 command.ExecuteNonQuery(); 62 } 63 //varTrans.Commit(); 64 } 65 catch (Exception ex) 66 { 67 //varTrans.Rollback(); 68 throw ex; 69 } 70 finally 71 { 72 conn.Close(); 73 } 74 } 75 }
到此结束!
作者:DotNet码农
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.