mysql用php分割多查询字符串
我想创建一个数据库恢复功能,它将解析用 phpMyAdmin 生成的转储并执行所有查询。
我已经有一个执行查询的 MySQL 类,但它只知道如何执行单个查询。 我正在寻找一种将文件内容拆分为单个查询的方法。
我尝试使用 preg_split ...但没能让它工作。
$queries = preg_split('/[(.+);\s*\n/', $content, -1, PREG_SPLIT_NO_EMPTY);
我不太擅长正则表达式。 有什么方法可以实现我的目标吗?
I want to make a database restore function that will parse a dump made with phpMyAdmin and will execute all of the queries.
I already have a MySQL class that does the query, but it only knows how to do a single query. I am looking of a way to split the file content into single queries.
I tried to play with preg_split ... but didn't managed to get it to work.
$queries = preg_split('/[(.+);\s*\n/', $content, -1, PREG_SPLIT_NO_EMPTY);
I am not very good with regular expressions. Is there a way I can accomplish my goal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要尝试用正则表达式解析sql。 如果 sql 字符串中的某处有
;
怎么办?我会尝试http://pear.php.net/package/SQL_Parser,或任何其他 php mysql 解析器。 另请参阅 PHP MySQL SQL 解析器(INSERT 和 UPDATE) 此处。
don't try to parse sql with regular expressions. what if there is a
;
somewhere inside a sql string?i would try http://pear.php.net/package/SQL_Parser, or any of the other php mysql parsers out there. see also PHP MySQL SQL parser (INSERT and UPDATE) here on SO.
我认为当 $content 中有存储过程、函数或触发器时,分割上面的注释会产生错误的字符串。
I think splitting in comments above will make bad strings when you have stored procedures, functions or triggers in $content.
最终我设法找到了正确的正则表达式:
它在 ; 之后分割查询。 符号并且即使查询分布在多行上或查询包含 ; 也不会中断 因为它在行尾查找它。
Eventually I managed to find the right regex:
it splits the query after the ; sign and does not break even if the query spreads on multiple rows or the query contains ; since it looks for it at the end of a line.