c# 如何执行mysql命令 导出mysql脚本和导入mysql脚本
我这里有个C# 读取sql脚本文件并执行的方法:
2个参数,connectionstr 为数据库的连接字符串 、path 为sql 脚本文件所在位置
对sql 脚本的要求是, 记得用'GO' 关键词 ,作为一个逻辑片段的分割,
比如:
select * from xx GO insert xxx(aa,b,bcc) values(xx,xx,xx) GO
方法实现如下:
public static void ExecuteSqlServerScriptFile(string connectionstr, string path) { Stream stream = File.OpenRead(path); StreamReader reader = null; var builder = new StringBuilder(); var connection = new SqlConnection(connectionstr); reader = new StreamReader(stream); try { connection.Open(); string sqlString; while ((sqlString = reader.ReadLine()) != null) { if (sqlString.Trim().ToUpper() != @"GO" && sqlString.Trim() != "") { builder.AppendLine(sqlString); } else if (builder.ToString().Trim() != "") { var command = new SqlCommand(builder.ToString(), connection); command.ExecuteNonQuery(); builder.Remove(0, builder.Length); } } } finally { connection.Close(); reader.Close(); } }
http://172.18.0.3:81/phpMyAdmin/index.php?token=4e306bd0a7ccfec8cd6b43142f47d048#PMAURL-0:index.php?db=&table=&server=1&target=&token=4e306bd0a7ccfec8cd6b43142f47d048 ; 可以使用在线工具进行导出mysql脚本和导入mysql脚本。我原来是这么用的。
//使用mysql 应该用MySqlConnection public static int ExecuteQuery(string sql,CommandType type,params MySqlParameter[] pms) { using (MySqlConnection con = new MySqlConnection(ConnStr)) { using (MySqlCommand cmd=new MySqlCommand(sql,con)) { if (pms!=null) { cmd.Parameters.AddRange(pms); } cmd.CommandType = type; con.Open(); return cmd.ExecuteNonQuery(); } } }