├── .github
├── dependabot.yml
└── workflows
│ ├── main.yml
│ ├── php.yml
│ └── release.yml
├── .gitignore
├── LICENSE
├── README.md
├── README_EN.md
├── composer.json
├── logo.svg
├── phpunit.xml
├── src
└── MysqlHelper.php
└── tests
├── MysqlHelperTest.php
└── import.sql
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | - package-ecosystem: "composer" # See documentation for possible values
9 | directory: "/" # Location of package manifests
10 | schedule:
11 | interval: "daily"
12 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | branches:
4 | - main
5 |
6 | jobs:
7 | contrib-readme-job:
8 | runs-on: ubuntu-latest
9 | name: A job to automate contrib in readme
10 | permissions:
11 | contents: write
12 | pull-requests: write
13 | steps:
14 | - name: Contribute List
15 | uses: akhilmhdh/contributors-readme-action@v2.3.10
16 | env:
17 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
--------------------------------------------------------------------------------
/.github/workflows/php.yml:
--------------------------------------------------------------------------------
1 | name: PHP Composer
2 |
3 | on:
4 | push:
5 | branches: [ "main" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | permissions:
10 | contents: read
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - uses: actions/checkout@v3
19 |
20 | - name: Validate composer.json and composer.lock
21 | run: composer validate --strict
22 |
23 | - name: Cache Composer packages
24 | id: composer-cache
25 | uses: actions/cache@v3
26 | with:
27 | path: vendor
28 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
29 | restore-keys: |
30 | ${{ runner.os }}-php-
31 |
32 | - name: Install dependencies
33 | run: composer install --prefer-dist --no-progress
34 |
35 | # Add a test script to composer.json, for instance: "test": "vendor/bin/phpunit"
36 | # Docs: https://getcomposer.org/doc/articles/scripts.md
37 |
38 | # - name: Run test suite
39 | # run: composer run-script test
40 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 |
3 | on:
4 | push:
5 | tags:
6 | - v*
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Auto Release
13 | uses: "marvinpinto/action-automatic-releases@latest"
14 | with:
15 | repo_token: "${{ secrets.GITHUB_TOKEN }}"
16 | draft: true
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor
2 | .idea
3 | composer.lock
4 | .phpunit.result.cache
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 zjkal
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 中文 | English
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | `MysqlHelper` 是一个便捷的`通过PHP导入和导出Mysql数据库表结构和数据`的工具,可以快速实现mysql的数据库的导入和导出. 此类库旨在提供轻量化便捷的mysql导入导出, 开发初衷是web应用安装程序和插件类应用的数据结构导入. 因此没有做数据分批, 大量数据的导入导出并不适合.
27 |
28 | ## 🧩特性
29 |
30 | - 简单易用: 仅依赖`mysqlli`扩展,`开箱即用`
31 | - 灵活操作: 兼容主流框架,使用更方便
32 | - 长期维护: 作者为自由职业者,保证项目的`长期稳定`和`持续更新`
33 |
34 | ## 🚀安装
35 |
36 | 通过Composer导入类库
37 |
38 | ```bash
39 | composer require zjkal/mysql-helper
40 | ```
41 |
42 | ## 🌈使用文档
43 |
44 | ### 1. 实例化
45 |
46 | *方式一: 常规方法*
47 |
48 | ```php
49 | use zjkal\MysqlHelper;
50 |
51 | $mysql = new MysqlHelper('root', 'passwd', 'dbname', '127.0.0.1', '3306', 'utf8mb4', 'wp_');
52 | ```
53 |
54 | *方式二: 实例化后,通过setConfig方法设置数据库配置*
55 |
56 | ```php
57 | $mysql = new MysqlHelper();
58 | $mysql->setConfig(['username' => 'root', 'password' => 'passwd', 'database' => 'dbname']);
59 | ```
60 |
61 | MysqlHelper针对常用的框架做了兼容,可以直接使用框架的数据库配置, 比如`ThinkPHP`框架或`Laravel`框架
62 |
63 | ```php
64 | $mysql = new MysqlHelper();
65 | $config = config('database.connections.mysql');
66 | $mysql->setConfig($config);
67 | ```
68 |
69 | ### 2. 导出数据
70 |
71 | * 如果实例化时, 已经设置了表前缀,导出的表名可以不用带前缀
72 |
73 | ```php
74 | //导出数据库(包含表结构和数据)
75 | $mysql->exportSqlFile('test.sql');
76 |
77 | //仅导出数据库表结构
78 | $mysql->exportSqlFile('test.sql', false);
79 |
80 | //导出指定表的结构和数据
81 | $mysql->exportSqlFile('test.sql', true, ['table1', 'table2']);
82 |
83 | //导出数据库所有表,并且添加禁用外键检查的SQL语句
84 | $mysql->exportSqlFile('test.sql', true, [], true);
85 | //php8以上可以更简洁的写法:
86 | $mysql->exportSqlFile('test.sql', disableForeignKeyChecks: true);
87 | ```
88 |
89 | ### 3. 导入数据
90 |
91 | * 如果需要在导入过程中自定义表前缀, 则sql文件中的表前缀需要使用`__PREFIX__`占位符代替
92 | * 如果实例化时, 已经设置了表前缀, 则可以不用传入第二个参数
93 | * 增加了数据导入时的参数, 用于设置是否删除已存在的表, 默认不删除, 一般用于数据恢复.
94 |
95 | ```php
96 | //导入数据库
97 | $mysql->importSqlFile('test.sql');
98 |
99 | //导入数据库,并自动替换表前缀
100 | $mysql->importSqlFile('test.sql', 'wp_');
101 |
102 | //导入数据库,不替换前缀, 并且如果表已经存在,则先删除
103 | $mysql->importSqlFile('test.sql', '', true);
104 | //php8以上可以更简洁的写法:
105 | $mysql->importSqlFile('test.sql', dropTableIfExists: true);
106 | ```
107 |
108 | ## 📃更新日志
109 |
110 | > v1.0.9 2024年12月5日
111 | > * 增加了数据导入时的参数, 用于设置是否删除已存在的表
112 |
113 | > v1.0.8 2024年11月23日
114 | > * 修复了导入表时重复替换忽略语句的BUG
115 |
116 | > v1.0.7 2024年10月4日
117 | > * 增加导入的稳定性:过滤空行
118 |
119 | > v1.0.6 2024年8月27日
120 | > * 导入时增加了判断是否存在同名表的逻辑
121 |
122 | > v1.0.5 2024年6月14日
123 | > * 增加了在导出时可以设置禁用外键检查的参数
124 |
125 | 点击查看更多
126 |
127 | > v1.0.4 2024年4月19日
128 | > * 优化了.sql文件中注释的过滤规则
129 |
130 | > v1.0.3 2023年12月9日
131 | > * 实例化时如果已经设置了表前缀,导出的表名可以不包含前缀
132 |
133 | > v1.0.2 2023年9月23日
134 | > * 增加了数据导出的稳定性
135 |
136 | > v1.0.1 2023年9月10日
137 | > * 修复了在Thinkphp框架下端口识别错误的BUG
138 | > * 增加了导入的稳定性
139 |
140 | > v1.0.0 2023年9月2日
141 | > * 首次发布
142 |
143 |
144 | ## 😎开发者们
145 |
146 |
147 |
167 |
168 |
169 | ## 🐧QQ频道
170 |
171 |
172 |
173 |
174 |
175 | ## 📖开源协议
176 |
177 | MysqlHelper遵循[MIT开源协议](https://github.com/zjkal/mysql-helper/blob/main/LICENSE), 意味着您无需任何授权, 即可免费将MysqlHelper应用到您的项目中
178 |
--------------------------------------------------------------------------------
/README_EN.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 中文 | English
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | 'MysqlHelper' is a convenient tool for 'importing and exporting Mysql database table structure and data via PHP', which can quickly import and export mysql databases. These libraries are designed to provide lightweight and convenient MySQL import and export, and are developed to import data structures from web application installers and plug-in applications. Therefore, there is no data batching, and the import and export of a large amount of data is not suitable.
27 |
28 | ## 🧩Features
29 |
30 | - Easy to use: only depends on `mysqlli` extension, `out of the box`
31 | - Flexible operation: Compatible with mainstream frameworks, more convenient to use
32 | - Long-term maintenance: The author is a freelancer committed to ensuring the project's `long-term stability` and `continuous updates`.
33 |
34 | ## 🚀Installation
35 |
36 | Install via Composer.
37 |
38 | ```bash
39 | composer require zjkal/mysql-helper
40 | ```
41 |
42 | ## 🌈Usage
43 |
44 | ### 1. instantiate
45 |
46 | *Method 1: Conventional method*
47 |
48 | ```php
49 | use zjkal\MysqlHelper;
50 |
51 | $mysql = new MysqlHelper('root', 'passwd', 'dbname', '127.0.0.1', '3306', 'utf8mb4', 'wp_');
52 | ```
53 |
54 | *Method 2: After instantiation, set the database configuration through the setConfig method*
55 |
56 | ```php
57 | $mysql = new MysqlHelper();
58 | $mysql->setConfig(['username' => 'root', 'password' => 'passwd', 'database' => 'dbname']);
59 | ```
60 |
61 | MysqlHelper is compatible with commonly used frameworks, you can directly use the database configuration of the framework, such as `ThinkPHP` framework or `Laravel` framework
62 |
63 | ```php
64 | $mysql = new MysqlHelper();
65 | $config = config('database.connections.mysql');
66 | $mysql->setConfig($config);
67 | ```
68 |
69 | ### 2. export
70 |
71 | ```php
72 | //Export database (including table structure and data)
73 | $mysql->exportSqlFile('test.sql');
74 |
75 | //Export only the database table structure
76 | $mysql->exportSqlFile('test.sql', false);
77 |
78 | //Export the structure and data of the specified table
79 | $mysql->exportSqlFile('test.sql', true, ['table1', 'table2']);
80 |
81 | //Export all tables in the database and add an SQL statement that disables foreign key checking
82 | $mysql->exportSqlFile('test.sql', true, [], true);
83 | //PHP8 or above can be written more concisely:
84 | $mysql->exportSqlFile('test.sql', disableForeignKeyChecks: true);
85 | ```
86 |
87 | ### 3. Import
88 |
89 | * If you need to customize the table prefix during the import process, the table prefix in the SQL file needs to be replaced with a '__PREFIX__' placeholder
90 | * If the database prefix has been set during instantiation, you do not need to pass in the second parameter
91 |
92 | ```php
93 | import database
94 | $mysql->importSqlFile('test.sql');
95 |
96 | //Import the database and automatically replace the table prefix
97 | $mysql->importSqlFile('test.sql', 'wp_');
98 |
99 | //Import the database, do not replace the prefix, and delete the table first if it already exists
100 | $mysql->importSqlFile('test.sql', '', true);
101 | //PHP8 or above can be written more concisely:
102 | $mysql->importSqlFile('test.sql', dropTableIfExists: true);
103 | ```
104 |
105 | ## 📃Changelog
106 |
107 | > v1.0.9 December 5, 2024
108 | > * Added parameters for data import to set whether to delete existing tables
109 |
110 | > v1.0.8 November 23, 2024
111 | > * Fixed the bug that the ignore statement was repeatedly replaced when importing a table
112 |
113 | > v1.0.7 Oct 4, 2024
114 | > * Improved the stability of imports: filter blank rows
115 |
116 | > v1.0.6 Aug 27, 2024
117 | > * Added logic to determine whether a table with the same name exists
118 |
119 | > v1.0.5 June 14, 2024
120 | > * Added the ability to set a parameter to disable foreign key checking during export
121 |
122 | 点击查看更多
123 |
124 | > v1.0.4 Apr 19, 2024
125 | > * Optimized the filtering rules for comments in .sql files
126 |
127 | > v1.0.3 Dec 9, 2023
128 | > * If a table prefix is set during instantiation, the exported table name can not contain the prefix
129 |
130 | > v1.0.2 Sep 23, 2023
131 | > * Increased export stability
132 |
133 | > v1.0.1 Sep 10, 2023
134 | > * Fixed the bug of incorrect port recognition under the Thinkphp framework
135 | > * Increased import stability
136 |
137 | > v1.0.0 Sep 2, 2023
138 | > * Initial Release
139 |
140 |
141 | ## 😎Contributors
142 |
143 |
144 |
164 |
165 |
166 | ## 📖License
167 |
168 | The MIT License (MIT). Please see [License File](https://github.com/zjkal/mysql-helper/blob/main/LICENSE) for more information.
169 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "zjkal/mysql-helper",
3 | "description": "一个便捷的MySQL导入导出的助手类库。 a mysql import and export helper library.",
4 | "keywords": ["php", "mysql", "helper", "import", "export", "zjkal"],
5 | "type": "library",
6 | "license": "MIT",
7 | "authors": [
8 | {
9 | "name": "zjkal",
10 | "email": "zjkal@qq.com"
11 | }
12 | ],
13 | "minimum-stability": "dev",
14 | "require": {
15 | "php": ">=7.1",
16 | "ext-mysqli": "*"
17 | },
18 | "require-dev": {
19 | "phpunit/phpunit": "@stable"
20 | },
21 | "autoload": {
22 | "psr-4": {
23 | "zjkal\\": "src/"
24 | }
25 | },
26 | "autoload-dev": {
27 | "psr-4": {
28 | "zjkal\\tests\\": "tests/"
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/phpunit.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 | ./tests/
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/MysqlHelper.php:
--------------------------------------------------------------------------------
1 | username = $username;
66 | $this->password = $password;
67 | $this->database = $database;
68 | $this->host = $host;
69 | $this->port = intval($port);
70 | $this->prefix = $prefix;
71 | $this->charset = $charset;
72 | }
73 |
74 | /**
75 | * @param array $config 设置参数
76 | * @return void
77 | */
78 | public function setConfig(array $config = [])
79 | {
80 | if (empty($config)) {
81 | throw new InvalidArgumentException('配置数组不能为空');
82 | }
83 | if (empty($config['username']) || empty($config['password']) || empty($config['database'])) {
84 | throw new InvalidArgumentException('配置数据必须包含用户名,密码和数据库名');
85 | }
86 | $this->__construct(
87 | $config['username'],
88 | $config['password'],
89 | $config['database'],
90 | $config['host'] ?? $config['hostname'] ?? '127.0.0.1',
91 | $config['port'] ?? $config['hostport'] ?? 3306,
92 | $config['prefix'] ?? '',
93 | $config['charset'] ?? 'utf8mb4'
94 | );
95 | }
96 |
97 | /**
98 | * 将.sql文件导入到mysql数据库
99 | * @param string $sqlFilePath .sql文件路径
100 | * @param string $prefix 表前缀(优先级高于构造函数中的表前缀,默认为空)
101 | * @param bool $dropTableIfExists 如果表已存在,是否先删除(默认为false)
102 | * @return void
103 | */
104 | public function importSqlFile(string $sqlFilePath, string $prefix = '', bool $dropTableIfExists = false)
105 | {
106 |
107 | if (!file_exists($sqlFilePath)) {
108 | throw new InvalidArgumentException('sql文件不存在');
109 | }
110 |
111 | $prefix = $prefix ?: $this->prefix;
112 |
113 | // 创建MySQL连接
114 | $conn = new mysqli($this->host, $this->username, $this->password, $this->database, $this->port);
115 |
116 | // 检查连接是否成功
117 | if ($conn->connect_error) {
118 | throw new \mysqli_sql_exception("数据库连接失败: " . $conn->connect_error);
119 | }
120 |
121 | // 设置编码
122 | $conn->set_charset($this->charset);
123 |
124 | // 读取.sql文件内容并过滤注释
125 | $sqlContent = file_get_contents($sqlFilePath);
126 | $sqlContent = preg_replace("/(\/\*.*?\*\/|--.*?$)/ms", '', $sqlContent);
127 | // 分割SQL语句
128 | $sqlContent = explode(";", $sqlContent);
129 | //去掉每条sql语句两边的空格和换行
130 | $sqlContent = array_map(function ($value) {
131 | return trim($value);
132 | }, $sqlContent);
133 | // 过滤空数组
134 | $sqlContent = array_filter($sqlContent);
135 |
136 | // 执行每个SQL语句
137 | foreach ($sqlContent as $sql) {
138 | // 替换表前缀
139 | if (!empty($prefix)) {
140 | $sql = str_ireplace('__PREFIX__', $prefix, $sql);
141 | }
142 |
143 | //判断如果是创建表的SQL语句
144 | if (stripos($sql, 'CREATE TABLE') !== false) {
145 | //判断如果表已经存在是否先删除
146 | if ($dropTableIfExists) {
147 | //提取出表的名称
148 | preg_match('/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?`?(\w+)`?/i', $sql, $matches);
149 | $tableName = $matches[1];
150 | //删除表
151 | $conn->query("DROP TABLE IF EXISTS `$tableName`");
152 | } else {
153 | // 忽略已经存在的表结构
154 | if (stripos($sql, 'CREATE TABLE IF NOT EXISTS') === false) {
155 | $sql = str_ireplace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $sql);
156 | }
157 | }
158 | }
159 |
160 | // 忽略插入重复数据
161 | if (stripos($sql, 'INSERT IGNORE INTO') === false) {
162 | $sql = str_ireplace('INSERT INTO', 'INSERT IGNORE INTO', $sql);
163 | }
164 |
165 | $result = $conn->query($sql);
166 | if (!$result) {
167 | throw new \mysqli_sql_exception("导入失败: " . $conn->error);
168 | }
169 | }
170 |
171 | // 关闭连接
172 | $conn->close();
173 | }
174 |
175 | /**
176 | * 将mysql数据库表结构和数据导出为.sql文件
177 | * @param string $sqlFilePath 导出的.sql文件路径
178 | * @param bool $withData 是否导出表数据(默认为true)
179 | * @param array $tables 要导出的表名数组(默认为空,即导出所有表)
180 | * @Param bool $disableForeignKeyChecks 禁用外键检查(默认为false)
181 | * @return void
182 | */
183 | public function exportSqlFile(string $sqlFilePath, bool $withData = true, array $tables = [], bool $disableForeignKeyChecks = false)
184 | {
185 | // 创建MySQL连接
186 | $conn = new mysqli($this->host, $this->username, $this->password, $this->database, $this->port);
187 |
188 | // 检查连接是否成功
189 | if ($conn->connect_error) {
190 | throw new \mysqli_sql_exception("数据库连接失败: " . $conn->connect_error);
191 | }
192 |
193 | // 设置编码
194 | $conn->set_charset($this->charset);
195 |
196 | // 获取所有表名
197 | $result = $conn->query("SHOW TABLES");
198 | $all_tables = [];
199 |
200 | while ($row = $result->fetch_row()) {
201 | $all_tables[] = $row[0];
202 | }
203 |
204 | // 打开输出文件
205 | $outputFile = fopen($sqlFilePath, 'w');
206 |
207 | // 设置禁用外键检查
208 | if ($disableForeignKeyChecks) {
209 | fwrite($outputFile, "SET FOREIGN_KEY_CHECKS=0;\n");
210 | }
211 |
212 | // 循环每个表,导出结构和数据
213 | foreach ($all_tables as $table) {
214 | if (!empty($tables) && !in_array($table, $tables)) {
215 | continue;
216 | }
217 | //如果设置了表前缀,且传入的表名不包含表前缀,则补上
218 | if (!empty($this->prefix) && strpos($table, $this->prefix) !== 0) {
219 | $table = $this->prefix . $table;
220 | }
221 |
222 | // 导出表结构
223 | fwrite($outputFile, "-- 表结构:$table\n");
224 | $createTableSQL = $conn->query("SHOW CREATE TABLE $table");
225 | $createTableRow = $createTableSQL->fetch_row();
226 | fwrite($outputFile, $createTableRow[1] . ";\n");
227 |
228 | if ($withData) {
229 | // 导出表数据
230 | $result = $conn->query("SELECT * FROM $table");
231 | if (!$result) {
232 | fwrite($outputFile, "/* 查询失败或" . $table . "表不存在 */\n");
233 | } else if ($result->num_rows == 0) {
234 | fwrite($outputFile, "/* " . $table . "表没有数据 */\n");
235 | } else {
236 | fwrite($outputFile, "-- 表数据:$table\n");
237 | while ($row = $result->fetch_assoc()) {
238 | $escapedValues = array_map(function ($value) use ($conn) {
239 | return $conn->escape_string(strval($value));
240 | }, $row);
241 | $columns = implode("','", $escapedValues);
242 | fwrite($outputFile, "INSERT INTO `$table` VALUES ('$columns');\n");
243 | }
244 | //释放结果集
245 | $result->free();
246 | }
247 | }
248 | }
249 |
250 | // 关闭文件和连接
251 | fclose($outputFile);
252 | $conn->close();
253 | }
254 | }
255 |
--------------------------------------------------------------------------------
/tests/MysqlHelperTest.php:
--------------------------------------------------------------------------------
1 | 'root', 'password' => 'root', 'database' => 'testdatabase'];
11 |
12 | public function testImportSqlFile()
13 | {
14 | $this->expectOutputString('导入成功');
15 |
16 | try {
17 | $mysql = new MysqlHelper();
18 | $mysql->setConfig($this->config);
19 | $mysql->importSqlFile('import.sql', 'test_', true);
20 | print '导入成功';
21 | } catch (\Exception $e) {
22 | $this->fail('导入失败:' . $e->getMessage());
23 | }
24 | }
25 |
26 | public function testExportSqlFile()
27 | {
28 | $this->expectOutputString('导出成功');
29 |
30 | try {
31 | $mysql = new MysqlHelper();
32 | $mysql->setConfig($this->config);
33 | $mysql->exportSqlFile('export.sql', true, [], true);
34 | print '导出成功';
35 | } catch (\Exception $e) {
36 | $this->fail('导出失败:' . $e->getMessage());
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/tests/import.sql:
--------------------------------------------------------------------------------
1 | -- 表结构:shop
2 | CREATE TABLE IF NOT EXISTS `__PREFIX__shop` (
3 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
4 | `name` varchar(255) DEFAULT NULL COMMENT '商品名称',
5 | `price` decimal(10,2) DEFAULT NULL COMMENT '价格',
6 | PRIMARY KEY (`id`)
7 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
8 | -- 表数据:shop
9 | INSERT INTO `__PREFIX__shop` VALUES ('1','可口可乐','2.99');
10 | INSERT INTO `__PREFIX__shop` VALUES ('2','溜溜梅','5.99');
11 | -- 表结构:user
12 | CREATE TABLE IF NOT EXISTS `__PREFIX__user` (
13 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
14 | `username` varchar(255) DEFAULT NULL COMMENT '用户名',
15 | `password` varchar(255) DEFAULT NULL COMMENT '密码',
16 | `status` int(1) DEFAULT NULL COMMENT '状态',
17 | PRIMARY KEY (`id`)
18 | ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
19 | -- 表数据:user
20 | INSERT INTO `__PREFIX__user` VALUES ('1','admin','admin','1');
21 | INSERT INTO `__PREFIX__user` VALUES ('2','test','test','1');
22 |
--------------------------------------------------------------------------------