C#通过读取Mysql脚本创建数据库
#region script helper private bool ExecuteScriptFile(string pathToScriptFile, out string errorMsg) { StreamReader reader = null; DbConnection connection = null; string strSql; string applicationPath = Request.ApplicationPath; using (reader = new StreamReader(pathToScriptFile)) { using (connection = new MySqlConnection(GetConnectionString())) { DbCommand dbCmd = connection.CreateCommand(); dbCmd.Connection = connection; dbCmd.CommandType = CommandType.Text; dbCmd.CommandTimeout = 360; // 考虑到安装脚本可能比较大,将命令超时时间设为6分钟 connection.Open(); while (!reader.EndOfStream) { try { strSql = NextSqlFromStream(reader); if (!string.IsNullOrEmpty(strSql)) { dbCmd.CommandText = strSql.Replace("$VirsualPath$", applicationPath); dbCmd.ExecuteNonQuery(); } } catch (Exception ex) { throw new Exception(ex.Message); } } connection.Close(); } reader.Close(); } errorMsg = null; return true; } private static string NextSqlFromStream(StreamReader reader) { StringBuilder sb = new StringBuilder(); string lineOfText = reader.ReadLine().Trim(); while (!reader.EndOfStream && string.Compare(lineOfText, "GO", true, CultureInfo.InvariantCulture) != 0) { sb.Append(lineOfText + Environment.NewLine); lineOfText = reader.ReadLine(); } // 如果最后一句不是GO,添加最后一句 if (string.Compare(lineOfText, "GO", true, CultureInfo.InvariantCulture) != 0) sb.Append(lineOfText + Environment.NewLine); return sb.ToString(); } #endregion
/// <summary> /// 执行Sql文件 /// </summary> /// <param name="varFileName">sql文件</param> /// <param name="Conn">连接字符串</param> /// <returns></returns> private bool ExecuteSqlFile(string varFileName, String Conn) { using (StreamReader reader = new StreamReader(varFileName, System.Text.Encoding.GetEncoding("utf-8"))) { MySqlCommand command; MySqlConnection Connection = new MySqlConnection(Conn); Connection.Open(); try { string line = ""; string l; while (true) { // 如果line被使用,则设为空 if (line.EndsWith(";")) line = ""; l = reader.ReadLine(); // 如果到了最后一行,则退出循环 if (l == null) break; // 去除空格 l = l.TrimEnd(); // 如果是空行,则跳出循环 if (l == "") continue; // 如果是注释,则跳出循环 if (l.StartsWith("--")) continue; // 行数加1 line += l; // 如果不是完整的一条语句,则继续读取 if (!line.EndsWith(";")) continue; if (line.StartsWith("/*!")) { continue; } //执行当前行 command = new MySqlCommand(line, Connection); command.ExecuteNonQuery(); } } finally { Connection.Close(); } } return true; }
以上两种方法通过测试都可以实现。
第一种:先整个读取mysql脚本,同时执行多个创建
第二种:通过循环,先导入一个表结构及数据后再导入另一个(一个一个获取)