mysql 转储数据库,MySQL:从SQL查询中转储数据库

I'm writing a test framework in which I need to capture a MySQL database state (table structure, contents etc.).

I need this to implement a check that the state was not changed after certain operations. (Autoincrement values may be allowed to change, but I think I'll be able to handle this.)

The dump should preferably be in a human-readable format (preferably an SQL code, like mysqldump does).

I wish to limit my test framework to use a MySQL connection only. To capture the state it should not call mysqldump or access filesystem (like copy *.frm files or do SELECT INTO a file, pipes are fine though).

As this would be test-only code, I'm not concerned by the performance. I do need reliable behavior though.

What is the best way to implement the functionality I need?

I guess I should base my code on some of the existing open-source backup tools... Which is the best one to look at?

Update: I'm not specifying the language I write this in (no, that's not PHP), as I don't think I would be able to reuse code as is — my case is rather special (for practical purposes, lets assume MySQL C API). Code would be run on Linux.

解决方案

Given your requirements, I think you are left with (pseudo-code + SQL)

tables = mysql_fetch "SHOW TABLES"

foreach table in tables

create = mysql_fetch "SHOW CREATE TABLE table"

print create

rows = mysql_fetch "SELECT * FROM table"

foreach row in rows

// or could use VALUES (v1, v2, ...), (v1, v2, ...), .... syntax (maybe preferable for smaller tables)

insert = "INSERT (fiedl1, field2, field2, etc) VALUES (value1, value2, value3, etc)"

print insert

Basically, fetch the list of all tables, then walk each table and generate INSERT statements for each row by hand (most apis have a simple way to fetch the list of column names, otherwise you can fall back to calling DESC TABLE).

SHOW CREATE TABLE is done for you, but I'm fairly certain there's nothing analogous to do SHOW INSERT ROWS.

And of course, instead of printing the dump you could do whatever you want with it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值