微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!
xtrabackup备份MySQL备份与恢复
xtrabackup备份(MySQL备份)与恢复1. innobackupex参数选项--no-timestamp: 不创建一个时间戳--defaults-file=[MY.CNF] //指定配置文件:只能从给定的文件中读取默认选项。 且必须作为命令行上的第一个选项;必须是一个真实的文件,它不能是一个符号链接。--databases=# //指定备份的数据库和表,格式为:--database="db1[.tb1] db2[.tb2]" 多个库之间以空格隔开,如果此选项不被指定,将会备份所有的数据库。--include=REGEXP //用正则表达式的方式指定要备份的数据库和表,格式为 --include=‘^mydb[.]mytb’ ,对每个库中的每个表逐一匹配,因此会创建所有的库,不过是空的目录。--include 传递给 xtrabackup --tables。--tables-file=FILE //此选项的参数需要是一个文件名,此文件中每行包含一个要备份的表的完整名称,格式为databasename.tablename。该选项传递给 xtrabackup --tables-file,与--tables选项不同,只有要备份的表的库才会被创建。注意:部分备份(--include、--tables-file、--database)需要开启 innodb_file_per_table 。--compact //创建紧凑型备份,忽略所有辅助索引页,只备份data page;通过--apply-log中重建索引--rebuild-indexs。--compress //此选项指示xtrabackup压缩备份的InnoDB数据文件,会生成 *.qp 文件。--apply-log //应用 BACKUP-DIR 中的 xtrabackup_logfile 事务日志文件。一般情况下,在备份完成后,数据尚且不能用于恢复操作,因为备份的数据中可能会包含尚未提交的事务或已经提交但尚未同步至数据文件中的事务。因此,此时数据文件仍处于不一致状态。“准备”的主要作用正是通过回滚未提交的事务及同步已经提交的事务至数据文件使得数据文件处于一致性状态。--use-memory=# //此选项接受一个字符参数(1M/1MB,1G/1GB,默认100M),仅与--apply-log一起使用,该选项指定prepare时用于崩溃恢复(crash-recovery)的内存。--copy-back //拷贝先前备份所有文件到它们的原始路径。但原路径下不能有任何文件或目录,除非指定 --force-non-empty-directories 选项。--incremental-basedir=DIRECTORY //该选项接受一个字符串参数,该参数指定作为增量备份的基本数据集的完整备份目录。它与 --incremental 一起使用。--incremental-dir=DIRECTORY //该选项接受一个字符串参数,该参数指定了增量备份将与完整备份相结合的目录,以便进行新的完整备份。它与 --incremental 选项一起使用。--redo-only //在“准备基本完整备份” 和 “合并所有的增量备份(除了最后一个增备)”时使用此选项。它直接传递给xtrabackup的 xtrabackup --apply-log-only 选项,使xtrabackup跳过"undo"阶段,只做"redo"操作。如果后面还有增量备份应用到这个全备,这是必要的。有关详细信息,请参阅xtrabackup文档。--parallel=NUMBER-OF-THREADS //此选项接受一个整数参数,指定xtrabackup子进程应用于同时备份文件的线程数。请注意,此选项仅适用于文件级别,也就是说,如果您有多个.ibd文件,则它们将被并行复制; 如果您的表一起存储在一个表空间文件中,它将不起作用。2.全量备份恢复创建备份恢复的用户并赋权create user pxb@'localhost' identified by '123456';grant reload,process,lock tables,replication client on . to pxb@localhost;创建存放备份文件的目录mkdir -pv /var/data进行数据库全量备份:innobackupex --defaults-file=/etc/my.cnf --user=pxb --password=123456 /var/data/[root@aliy ~]# ll /var/data/2018-08-28_09-06-39/total 18460-rw-r----- 1 root root 417 Aug 28 09:06 backup-my.cnf-rw-r----- 1 root root 18874368 Aug 28 09:06 ibdata1drwxr-x--- 2 root root 4096 Aug 28 09:06 mysqldrwxr-x--- 2 root root 4096 Aug 28 09:06 performance_schemadrwxr-x--- 2 root root 4096 Aug 28 09:06 test-rw-r----- 1 root root 113 Aug 28 09:06 xtrabackup_checkpoints-rw-r----- 1 root root 454 Aug 28 09:06 xtrabackup_info-rw-r----- 1 root root 2560 Aug 28 09:06 xtrabackup_logfile全量备份恢复systemctl stop mariadbrm /var/lib/mysql -rfmkdir /var/lib/mysql准备一个完全备份: --apply-log,执行之后 xtrabackup_checkpoints 文件中的 backup_type = full-preparedinnobackupex --apply-log /var/data/2018-08-28_09-06-39/执行恢复操作:innobackupex --defaults-file=/etc/my.cnf --copy-back /var/data/2018-08-28_09-06-39/更改data目录权限并启动mysql:chown -R mysql:mysql /var/lib/mysqlsystemctl start mariadb3. 增量备份恢复所谓增量备份恢复就是在全量的基础上进行增量备份。增量备份1:以全量为基准innobackupex --defaults-file=/etc/my.cnf --user=pxb --password=123456 --incremental /var/data/inc --incremental-basedir=/var/data/2018-08-28_10-01-53/ --parallel=2中途进行了数据添加操作。增量备份2:以增量备份1为基准innobackupex --defaults-file=/etc/my.cnf --user=pxb --password=123456 --incremental /var/data/inc/ --incremental-basedir=/var/data/inc/2018-08-28_10-04-22/ --parallel=2增量备份的恢复:步骤:恢复完全备份恢复增量备份到完全备份(开始恢复的增量备份要添加--redo-only参数,到最后一次增量备份要去掉--redo-only)对整体的完全备份进行恢复,回滚提交的数据准备一个全备:innobackupex --apply-log --redo-only /var/data/2018-08-28_10-01-53/将增量1应用到完全备份innobackupex --apply-log --redo-only /var/data/2018-08-28_10-01-53 --incremental-dir=/var/data/inc/2018-08-28_10-04-22/将增量2应用到完全备份,不用加--redo-only参数innobackupex --apply-log /var/data/2018-08-28_10-01-53 --incremental-dir=/var/data/inc/2018-08-28_10-07-40/把所有的完全备份合并到一起进行一次apply操作,回滚提交的数据innobackupex --apply-log /var/data/2018-08-28_10-01-53/模拟:将数据库里的内容删除systemctl stop mariadbmv /var/lib/mysql /var/lib/mysql.bakmkdir /var/lib/mysql恢复:innobackupex --defaults-file=/etc/my.cnf --copy-back /var/data/2018-08-28_10-01-53/chown -R mysql:mysql /var/lib/mysqlsystemctl start maraidb流备份以及压缩备份Xtrabackup对备份的数据文件支持“流”功能,即可以将备份的数据通过STDOUT传输给tar程序进行归档,而不是默认的直接保存至某备份目录中。要使用此功能,仅需要使用--stream选项即可。如:innobackupex --stream=tar /data/backup/|gzip >/data/backup/`date +%F`.tar.gz也可以使用如下命令将数据备份至其他服务器innobackupex --default-file=/etc/my.cnf --stream=tar /backup | ssh [email protected] " cat -> /backups/date +%F_%H-%M-%S.tar"同时也可将备份的数据文件存储到远程的主机,使用--remote-host来实现innobackupex [email protected] /path/IN/REMOTE/HOST/to/backup
Beyond MySQL --Branching the popular database--转载
原文:http://www.ibm.com/developerworks/library/os-beyondmysql/IntroductionMySQL is one of the most popular free and open source programs in history. It's the database backbone for thousands of websites and could arguably be given credit (along with Linux®) for the explosive growth of the Internet over the past 10 years.So, if MySQL is so important, why is increasing amount of high profile off-shoots of the core MySQL product? Because MySQL is free and open source, developers have always been able to take the code, modify it as they see fit, and distribute it on their own. For a long time, there weren't any branches of MySQL that a developer would trust in their own production environment. However, that's changing rapidly. Several branches are getting a lot of attention.This article will discuss three popular branches of MySQL that are gaining attention: Drizzle, MariaDB, and Percona Server, including the XtraDB engine. This article will talk briefly about the reasons for each branch and their goals, and whether to use them in your own production environment. By the time you finish this article, you should be able to answer the question "Are these MySQL branch products a good solution for my environment?"Why branch?Why does MySQL need to be branched? That's a very legitimate question. Thousands of websites depend on it and it seems to be a good solution for many people. However, as is often the case, what's good for many people isn't good for all people. Some developers are motivated to make things better for their own needs. What could be better than turning a great solution into the perfect solution?Let's get into more specific details about what these branches sought to change. Some branches felt that MySQL was becoming too bloated and was offering many features that would never interest users, at the expense of simplicity of performance. If people were perfectly happy with the more streamlined MySQL 4, why should they deal with the additional complexity that was added with MySQL 5? For this branch, a preferred branch of MySQL would be simpler and faster — offer less features, but make them extremely quick, keeping in mind a target audience, in this case high availability websites.To other branches, MySQL wasn't offering enough new features, or were adding them too slowly. They may have felt that MySQL wasn't keeping up with its target markets of high availability websites running on multi-core processors with lots of RAM. As people familiar with MySQL know, it offers two different storage enginges — MyISAM and InnoDB. This branch felt that neither of these storage engines offered them exactly what they were looking for, so they created a new storage engine perfectly suited for their goals.Further, some branches have a top goal to be a "drop in" replacement to MySQL, where you could simply drop in their branch and not have to change one line of code. The branch uses the same code and interfaces as MySQL, making a transition as easy as possible. Yet, another branch boasts that it's not compatible with MySQL, requiring code changes. Each branch is also at a different maturity level, with some claiming they are production ready, and some claiming they are far from that goal at this point.Finally, there's uncertainty about how MySQL will fare under Oracle. Oracle bought Sun, who bought MySQL, and right now Oracle controls the MySQL product itself, and leads the development community in producing new finished products. Because Oracle already has a commercial database, there is concern that they may not put sufficient resources into MySQL to keep it cutting-edge. Therefore, many branches are also a result of the underlying fear that MySQL, the leading free and open source database, may see less features, slower release cycles, and more expensive support.XtraDBXtraDB is not a stand-alone product itself, but it is still considered a branch of MySQL. XtraDB is actually a storage engine for MySQL-based databases. This would be considered an additional storage engine to the standard MyISAM and InnoDB that are already a part of MySQL. MySQL 4 and 5 installs with each table using the default MyISAM storage engine. InnoDB is also a relatively newer option for a storage engine, and database administrators and developers can choose the types of storage engine, on a per table basis, when they set up the database. The major difference between the two storage engines is that MyISAM does not offer transactional support, while InnoDB does. Other differences are many small performance differences, with InnoDB offering many small performance improvements over MyISAM, and more reliability and safety when dealing with potential data loss. As it appears that InnoDB is the better-suited storage engine for future improvements, MySQL has switched the default storage engine to InnoDB instead of MyISAM starting with the 5.5 release.Building on these advantages, the InnoDB storage engine itself has been branched into a newer storage engine called XtraDB. Just how new is this storage engine? It was
SELECTs -- do's and don'ts
原文地址:http://mysql.rjweb.org/doc.php/ricksrotsBrought to you by Rick JamesHere are 160+ tips, tricks, suggestions, etc. They come from a decade of improving performance in MySQL in thousands of situations. There are exceptions to the statements below, but they should help guide you into better understanding how to effectively use MySQL. SELECTs -- do's and don'tsRoTsDiscussion    ⚈  Do not hide an indexed column inside a function call: DATE(x) = '...', LCASE(col) = 'foo'     ⚈  LCASE() is usually unnecessary because the collation will compare 'correctly' without it.     ⚈  #1: Subqueries perform poorly     ⚈  Never use "IN (SELECT...)" -- optimizes poorly. Turn into JOIN. (5.6.5 improves)     ⚈  A subquery that condenses data (GROUP BY, LIMIT, etc) may perform well     ⚈  OR may be very inefficient; turn into UNION.     ⚈  A coding pattern: dt >= '2010-02-01' AND dt < '2010-02-01' + INTERVAL 7 DAY     ⚈  ORDER BY NULL -- a little-known trick to avoid GROUP BY doing a sort (if there is another way).     ⚈  WHERE (a,b) > (7,8) is poorly optimized     ⚈  Gather these to study a slow query: SHOW CREATE TABLE, SHOW TABLE STATUS, EXPLAIN.     ⚈  Do not use OFFSET for pagination -- continue where you "left off"     ⚈  Don't mix DISTINCT and GROUP BY     ⚈  Be explicit about UNION ALL vs UNION DISTINCT -- it makes you think about which to use     ⚈  Do not use SELECT * except for debugging or when fetching into a hash.     ⚈  VIEWs are poorly optimized     ⚈  A subquery in the FROM clause may be useful for retrieving BLOBs without sorting them: Speed up a query by first finding the IDs, then self-JOIN to fetch the rest. Subqueries came to MySQL rather late in the game. They have not been well optimized, so it is usually better to turn your SELECTs into an equivalent JOIN. This is especially true for "IN ( SELECT ... )", but that is better optimized in 5.6.5 and MariaDB 5.5. Sometimes a subquery is really the best way to optimize a SELECT. The common thread of these "good" subqueries seems to be when the subquery has to scan a lot of rows, but boils down the intermediate resultset to a small number of rows. This is likely to happen with GROUP BY or LIMIT in the subquery. Index hints (FORCE INDEX, etc) may help you today, but may be the wrong thing for tomorrow -- different constants in the WHERE clause may lead FORCE to do the "wrong" thing. For analyzing a slow query, SHOW CREATE TABLE provides the datatypes, indexes, and engine. (DESCRIBE provides much less info.) SHOW TABLE STATUS tells how big the table is. EXPLAIN says how the query optimizer decided to perform the query. It is so tempting to use ORDER BY id LIMIT 30,10to find the 4th page of 10 items. But it is so inefficient, especially when you have thousands of pages. The thousandth page has to read (at some level) all the pages before it. "Left off" refers to having the "Next" button on one page give the id (or other sequencing info) of where the next page can be found. Then that page simply does WHERE id > $leftoff ORDER BY id LIMIT 10. More on pagination.INDEXingRoTsDiscussion    ⚈  #1: Start an INDEX with "="s from the WHERE clause, then one other thing (range, group, order)     ⚈  Terms: PRIMARY KEY > UNIQUE > INDEX = KEY     ⚈  An index _may_ speed up a SELECT by orders of magnitude and will slow down INSERTs a little. (A fair tradeoff?)     ⚈  Adding indexes is not a panacea.     ⚈  BTree is an excellent all-around indexing mechanism     ⚈  A BTree index node contains ~100 items. (1M rows = 3 levels; 1B rows = 5 levels)     ⚈  Flags, and other fields with few values, should not be alone in an index -- the index won't be used.     ⚈  MySQL rarely uses two INDEXes in one SELECT. Main exceptions: subqueries, UNION.     ⚈  A "prefix" index -- INDEX(name(10)) -- is rarely useful. Exception: TEXT     ⚈  A UNIQUE "prefix" is probably wrong -- UNIQUE(name(10)) forces 10 chars to be unique.     ⚈  It is ok to have Index_length > Data_length     ⚈  5 fields in a compound index seems "too many"     ⚈  Having no compound indexes is a clue that you do not understand their power. INDEX(a,b) may be much better than INDEX(a), INDEX(b)     ⚈  INDEX(a,b) covers for INDEX(a), so drop the latter.     ⚈  2x speedup when "Using index" (a "covering" index)     ⚈  Akiban (3rd party) "groups" tables together, interleaved, to improve JOIN performance.     ⚈  FULLTEXT (MyISAM) -- watch out for ft_min_word_len=4, stopwords, and 50% rule     ⚈  A FULLTEXT index will be used before any other index.     ⚈  FULLTEXT -- consider Syphinx, Lucene, etc (3rd Party) Indexing is very important to any database. Getting the "right" index can make a query run orders of magnitude faster. So, how to do that? Often "compound indexes" (multiple columns in a single INDEX(...)) are better than single-column indexes. A WHERE clause that has column=constant begs for an index that starts with that column. If the WHERE
那么什么是编码?什么是UTF-8?
http://www.infoq.com/cn/articles/in-mysql-never-use-utf8-use-utf8最近我遇到了一个bug,我试着通过Rails在以“utf8”编码的MariaDB中保存一个UTF-8字符串,然后出现了一个离奇的错误:Incorrect string value: ‘xF0x9Fx98x83 <…’ for column ‘summary’ at row 1我用的是UTF-8编码的客户端,服务器也是UTF-8编码的,数据库也是,就连要保存的这个字符串“ <…”也是合法的UTF-8。问题的症结在于,MySQL的“utf8”实际上不是真正的UTF-8。“utf8”只支持每个字符最多三个字节,而真正的UTF-8是每个字符最多四个字节。MySQL一直没有修复这个bug,他们在2010年发布了一个叫作“utf8mb4”的字符集,绕过了这个问题。 当然,他们并没有对新的字符集广而告之(可能是因为这个bug让他们觉得很尴尬),以致于现在网络上仍然在建议开发者使用“utf8”,但这些建议都是错误的。简单概括如下:MySQL的“utf8mb4”是真正的“UTF-8”。MySQL的“utf8”是一种“专属的编码”,它能够编码的Unicode字符并不多。我要在这里澄清一下:所有在使用“utf8”的MySQL和MariaDB用户都应该改用“utf8mb4”,永远都不要再使用“utf8”。那么什么是编码?什么是UTF-8?我们都知道,计算机使用0和1来存储文本。比如字符“C”被存成“01000011”,那么计算机在显示这个字符时需要经过两个步骤:计算机读取“01000011”,得到数字67,因为67被编码成“01000011”。计算机在Unicode字符集中查找67,找到了“C”。同样的:我的电脑将“C”映射成Unicode字符集中的67。我的电脑将67编码成“01000011”,并发送给Web服务器。几乎所有的网络应用都使用了Unicode字符集,因为没有理由使用其他字符集。Unicode字符集包含了上百万个字符。最简单的编码是UTF-32,每个字符使用32位。这样做最简单,因为一直以来,计算机将32位视为数字,而计算机最在行的就是处理数字。但问题是,这样太浪费空间了。UTF-8可以节省空间,在UTF-8中,字符“C”只需要8位,一些不常用的字符,比如“”需要32位。其他的字符可能使用16位或24位。一篇类似本文这样的文章,如果使用UTF-8编码,占用的空间只有UTF-32的四分之一左右。MySQL的“utf8”字符集与其他程序不兼容,它所谓的“”,可能真的是一坨……MySQL简史为什么MySQL开发者会让“utf8”失效?我们或许可以从提交日志中寻找答案。MySQL从4.1版本开始支持UTF-8,也就是2003年,而今天使用的UTF-8标准(RFC 3629)是随后才出现的。旧版的UTF-8标准(RFC 2279)最多支持每个字符6个字节。2002年3月28日,MySQL开发者在第一个MySQL 4.1预览版中使用了RFC 2279。同年9月,他们对MySQL源代码进行了一次调整:“UTF8现在最多只支持3个字节的序列”。是谁提交了这些代码?他为什么要这样做?这个问题不得而知。在迁移到Git后(MySQL最开始使用的是BitKeeper),MySQL代码库中的很多提交者的名字都丢失了。2003年9月的邮件列表中也找不到可以解释这一变更的线索。不过我可以试着猜测一下。2002年,MySQL做出了一个决定:如果用户可以保证数据表的每一行都使用相同的字节数,那么MySQL就可以在性能方面来一个大提升。为此,用户需要将文本列定义为“CHAR”,每个“CHAR”列总是拥有相同数量的字符。如果插入的字符少于定义的数量,MySQL就会在后面填充空格,如果插入的字符超过了定义的数量,后面超出部分会被截断。MySQL开发者在最开始尝试UTF-8时使用了每个字符6个字节,CHAR(1)使用6个字节,CHAR(2)使用12个字节,并以此类推。应该说,他们最初的行为才是正确的,可惜这一版本一直没有发布。但是文档上却这么写了,而且广为流传,所有了解UTF-8的人都认同文档里写的东西。不过很显然,MySQL开发者或厂商担心会有用户做这两件事:使用CHAR定义列(在现在看来,CHAR已经是老古董了,但在那时,在MySQL中使用CHAR会更快,不过从2005年以后就不是这样子了)。将CHAR列的编码设置为“utf8”。我的猜测是MySQL开发者本来想帮助那些希望在空间和速度上双赢的用户,但他们搞砸了“utf8”编码。所以结果就是没有赢家。那些希望在空间和速度上双赢的用户,当他们在使用“utf8”的CHAR列时,实际上使用的空间比预期的更大,速度也比预期的慢。而想要正确性的用户,当他们使用“utf8”编码时,却无法保存像“”这样的字符。在这个不合法的字符集发布了之后,MySQL就无法修复它,因为这样需要要求所有用户重新构建他们的数据库。最终,MySQL在2010年重新发布了“utf8mb4”来支持真正的UTF-8。为什么这件事情会让人如此抓狂因为这个问题,我整整抓狂了一个礼拜。我被“utf8”愚弄了,花了很多时间才找到这个bug。但我一定不是唯一的一个,网络上几乎所有的文章都把“utf8”当成是真正的UTF-8。“utf8”只能算是个专有的字符集,它给我们带来了新问题,却一直没有得到解决。总结如果你在使用MySQL或MariaDB,不要用“utf8”编码,改用“utf8mb4”。这里(https://mathiasbynens.be/notes/mysql-utf8mb4#utf8-to-utf8mb4)提供了一个指南用于将现有数据库的字符编码从“utf8”转成“utf8mb4”。英文原文:https://medium.com/@adamhooper/in-mysql-never-use-utf8-use-utf8mb4-11761243e434
linuxcentos上安装mysql教程,为需要远程登录的用户赋予权限
最近把之前学生时代的win server换成了linux(centos)系统,因为win对于部署一些项目时候比较麻烦,直接入正题 1、准备阶段我使用xshell工具管理服务器,相应下载和安装自行百度 2、安装接下来主要介绍Linux下使用yum安装MySQL,以及启动、登录和远程访问MySQL数据库。2.1安装mysql客户端yum install mysql如何出现下面这个,说明,已经安装了mysql 2.2安装mysql服务端yum install mysql-serveryum install mysql-devel在CentOS7上用上面的命令安装mysql服务端时,出现了以下的提示:原因是:CentOS7带有MariaDB而不是MySQL,MariaDB和MySQL一样也是开元的数据库,您可以使用yum -y install mariadb-server mariadb命令安装 解决方案:如果必须要安装MySQL,首先必须添加mysql社区repo通过输入命令:sudo rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm最后使用像安装MySQL的常规方法一样输入上面两行命令安装既可 2.3启动和停止1、数据库字符集设置,mysql配置文件/etc/my.cnf中加入default-character-set=utf82、启动mysql服务service mysqld start或者/etc/init.d/mysqld start 3、检查是否成功启动了mysql 4、停止mysqlservice mysqld stop 5、开机启动chkconfig -add mysqldchkconfig --list | grep mysql* //查看开机启动设置是否成功mysqld 0:关闭 1:关闭 2:启用 3:启用 4:启用 5:启用 6:关闭  2.4登录 1、创建root管理员mysqladmin -u root password 1234561.1创建普通用户 create user 用户名 identified by '密码';例:create user xiaogang identified by '123456'; 2、登陆mysql -u root -p输入密码即可。 3、忘记密码service mysqld stopmysqld_safe --user=root --skip-grant-tablesmysql -u rootuse mysqlupdate user set password=password("new_pass") where user="root";flush privileges; 2.5远程登陆开放防火墙的端口号1、为需要远程登录的用户赋予权限如何给用户分配权限grant 权限 on 数据库.数据表 to '用户' @ '主机名';(1)支持root用户允许远程连接mysql数据库grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;flush privileges;注意:root就拥有了所有的权限 (2)新建用户远程连接mysql数据库grant all on *.* to admin@'%' identified by '123456' with grant option;flush privileges;允许任何ip地址(%表示允许任何ip地址)的电脑用admin帐户和密码(123456)来访问这个mysql server。注意admin账户不一定要存在。注意:admin用户就拥有了所有的权限 (3)让 saucxs有查询 weekly数据库week_week 表的权限;grant select on weekly.week_week to 'saucxs'@'%'; (4)让saucxs有增删改查weekly数据库所有表的数据权限grant select,insert,update,delete on weekly.* to 'saucxs'@'%';注意:这个只有删除表中数据增删改查,而不是表的增删改查下面是我要进行建表操作,被拒绝了 (5)给电脑IP为10.163.225.87的用户saucxs分配可对数据库weekly的week_week表进行select,insert,update,delete,create,drop等操作的权限,并设定口令为123456。这样做的目的是只有在指定的电脑指定IP上才能登陆这个数据库账号。grant select,insert,update,delete,create,drop on weekly.week_week to [email protected];注意:这个create和drop 是指的数据库表的创建和删除,而不是数据表中数据新增和删除。 (6)如何收回mysql分配给别的用户的权限,一般指有root用户才具有该权限revoke 权限 on 数据库.数据表 from '用户'@'主机名'; 举个例子,回收查询功能,这样查询功能就失效了revoke select on weekly.* from 'saucxs'@'%'; (7)查看端口show global variables like 'port' centos7.x已经把3306端口开放了,并且不需要开启防火墙,直接用就行 
ContOS安装配置MySQL,redis
MySQL(MariaDB)一,说明MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可。开发这个分支的原因之一是:甲骨文公司收购了MySQL后,有将MySQL闭源的潜在风险,因此社区采用分支的方式来避开这个风险。也就是说MySQL即将要收费MariaDB是完全兼容MySQL的,包括API和命令行,使之能轻松成为MySQL的代替品。Red Hat Enterprise Linux/CentOS 7.0 发行版已将默认的数据库从 MySQL 切换到 MariaDB。二,添加 MariaDB yum 仓库当前环境:阿里云的yum源直接 yum install mariadb 发现版本特别低,还是5.5版本的,官方已经推出10.1版本了按照程序员的尿性,当然是下载官方最新版啦~# 首先在 RHEL/CentOS 和 Fedora 操作系统中添加 MariaDB 的 YUM 配置文件 MariaDB.repo 文件。mkdir mariadb.repo# 然后编辑创建mariadb.repo仓库文件vi /etc/yum.repos.d/MariaDB.repo# 再输入 i 进入编辑模式,添加repo仓库配置[mariadb]name = MariaDBbaseurl = http://yum.mariadb.org/10.1/centos7-amd64gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDBgpgcheck=1这里吐槽一波~官方服务器在国外,下载忒慢了!!三,安装MariaDB# 当 MariaDB 仓库地址添加好后,你可以通过下面的一行命令轻松安装 MariaDB。yum install MariaDB-server MariaDB-client -y启动MariaDB相关命令systemctl start mariadb #启动MariaDBsystemctl stop mariadb #停止MariaDBsystemctl restart mariadb #重启MariaDBsystemctl enable mariadb #设置开机启动四,初始化MariaDB在确认 MariaDB 数据库软件程序安装完毕并成功启动后请不要立即使用。为了确保数据 库的安全性和正常运转,需要先对数据库程序进行初始化操作。这个初始化操作涉及下面 5 个 步骤。➢ 设置 root 管理员在数据库中的密码值(注意,该密码并非 root 管理员在系统中的密 码,这里的密码值默认应该为空,可直接按回车键)。➢ 设置 root 管理员在数据库中的专有密码。➢ 随后删除匿名账户,并使用 root 管理员从远程登录数据库,以确保数据库上运行的业务的安全性。➢ 删除默认的测试数据库,取消测试数据库的一系列访问权限。➢ 刷新授权列表,让初始化的设定立即生效。注意: 确保mariadb服务器启动后,执行命令初始化mysql_secure_installation然后就是一路 Y 到底了。你也可以按照自己的需求进行配置 如:出现 Disallow root login remotely? [Y/n]  --> 禁止root用户从远程登录, 可以选<n>呀 !五,设置MariaDB支持中文MariaDB跟MySQL一样,数据库格式是拉丁文的,默认不支持中文我们得把它的数据格式改成 utf-8# 打开配置文件vim /etc/my.cnf# 先 dG 清空文件夹。没清空就按 g 回到首行, 再 dG 清空# 再按 i 进入编辑模式 复制如下代码[mysqld]character-set-server=utf8collation-server=utf8_general_cilog-error=/var/log/mysqld.logdatadir=/var/lib/mysqlsocket=/var/lib/mysql/mysql.sock# Disabling symbolic-links is recommended to prevent assorted security riskssymbolic-links=0# Settings user and group are ignored when systemd is used.# If you need to run mysqld under a different user or group,# customize your systemd unit file for mariadb according to the# instructions in http://fedoraproject.org/wiki/Systemd[client]default-character-set=utf8[mysql]default-character-set=utf8[mysqld_safe]log-error=/var/log/mariadb/mariadb.logpid-file=/var/run/mariadb/mariadb.pid## include all files from the config directory#!includedir /etc/my.cnf.d# 最后 按 Esc 键,进入命令模式, :wq! 保存强制退出就怕你忘记vim怎么操作了, 所以步骤都在里面了!贴心吧~六,登录注意:登录前先重启数据库systemctl restart mariadbmysql -uroot -p # 你没看错,这条就是登录命令# 登录后MariaDB [(none)]> s # 查看编码设置其它命令跟MySQl都一模一样不懂就去看我这篇MySQL的博客吧 redis安装一,yum安装#前提得配置好阿里云yum源,epel源#查看是否有redis包yum list redis#安装redisyum install redis -y#安装好,启动redissystemctl start redis没配置源的也还有两个方案:方案一:去看我上篇博客,配置国内源方案二:继续往下看 ⬇检查redis是否工作redis-cli #redis 客户端工具#进入交互式环境后,执行ping,返回pong表示安装成功127.0.0.1:6379> pingPONG二,源码编译安装redis# 1.下载redis源码, 可以 cd /opt 下载到此目录wget http://download.redis.io/releases/redis-4.0.10.tar.gz# 2.解压缩tar -zxf redis-4.0.10.tar.gz# 3.切换redis源码目录cd redis-4.0.10# 4.编译源文件make && make install# 5.启动redis服务端./redis-serverredis可执行文件的说明./redis-benchmark # 用于进行redis性能测试的工具./redis-check-dump #用于修复出问题的dump.rdb文件./redis-cli # redis的客户端./redis-server # redis的服务端./redis-check-aof # 用于修复出问题的AOF文件./redis-sentinel # 用于集群管理默认情况下,redis-server会以非daemon的方式来运行,且默认服务端口为6379。到这里,redis就可以正常运行啦~下面是关于安全方面的~三,切换redis端口目的:由于redis端口默认都是 6379,黑客可以利用这一点侵入你服务器,所以得换一个让它们想不到的端口来运行 redis再一个就是配置了redis以后,启动redis-server服务端得时候就不会默认挂载在哪里了, 它会在后台运行服务端, 你就可以不需要另外切换窗口去运行客户端了。# 1. 先切换到目标目录cd /opt/redis-4.0.10/# 2. 创建文件touch redis-6380.conf# 3. 创建文件夹mkdir 6380# 4. 打开这个文件vi /opt/redis-4.0.10/redis-6380.conf# 5. 按 i 进入编辑默认,复制下面代码port 6380 # 运行在6380的redis数据库实例daemonize yes # 后台运行redispidfile /opt/redis-4.0.10/6380/redis.pid # 存放redis pid的文件loglevel notice # 日志等级logfile "/opt/redis-4.0.10/6380/redis.log" # 指定redis日志文件的生成目录dir /opt/redis-4.0.10/6380 # 指定redis数据文件夹的目录protected-mode yesrequirepass 123 # 设置redis的密码,密码自己改# 然后 按 Esc 键,进入命令模式,输入 :wq! 保存并强制退出# 为了兼容性,复制的时候还是把注释删了把!!!你也可以根据自己的需求配置文件路径~此时启动redis服务端命令就变成这样了redis-server redis-6380.conf启动客户端命令也变了redis-cli -p 6380 -a 123# -p 设置redis链接的端口# -a 显示填写的密码# 或者redis-cli -p 6380auth 123注意: 启动以后先 ping 一下, 没显示 PONG,就说明没连接成功
数据库 -- mysql表操作
一,存储引擎介绍存储引擎即表类型,mysql根据不同的表类型会有不同的处理机制详见:https://www.cnblogs.com/peng104/p/9751738.html 二,表介绍表相当于文件,表中的一条记录就相当于文件的一行内容,不同的是,表中的一条记录有对应的标题,称为表的字段id,name,qq,age称为字段,其余的,一行内容称为一条记录 三,创建表create table 表名(字段名1 类型[(宽度) 约束条件],字段名2 类型[(宽度) 约束条件],字段名3 类型[(宽度) 约束条件]);#注意:1. 在同一张表中,字段名是不能相同2. 宽度和约束条件可选3. 字段名和类型是必须的MariaDB [(none)]> create database db1 charset utf8;MariaDB [(none)]> use db1;MariaDB [db1]> create table t1(-> id int,-> name varchar(50),-> sex enum('male','female'),-> age int(3)-> );MariaDB [db1]> show tables; #查看db1库下所有表名MariaDB [db1]> desc t1;+-------+-----------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-----------------------+------+-----+---------+-------+| id | int(11) | YES | | NULL | || name | varchar(50) | YES | | NULL | || sex | enum('male','female') | YES | | NULL | || age | int(3) | YES | | NULL | |+-------+-----------------------+------+-----+---------+-------+MariaDB [db1]> select id,name,sex,age from t1;Empty set (0.00 sec)MariaDB [db1]> select * from t1;Empty set (0.00 sec)MariaDB [db1]> select id,name from t1;Empty set (0.00 sec)View CodeMariaDB [db1]> insert into t1 values-> (1,'egon',18,'male'),-> (2,'alex',81,'female')-> ;MariaDB [db1]> select * from t1;+------+------+------+--------+| id | name | age | sex |+------+------+------+--------+| 1 | egon | 18 | male || 2 | alex | 81 | female |+------+------+------+--------+MariaDB [db1]> insert into t1(id) values-> (3),-> (4);MariaDB [db1]> select * from t1;+------+------+------+--------+| id | name | age | sex |+------+------+------+--------+| 1 | egon | 18 | male || 2 | alex | 81 | female || 3 | NULL | NULL | NULL || 4 | NULL | NULL | NULL |+------+------+------+--------+View Code注意:表中的最后一个字段不要加逗号  四,查看表结构MariaDB [db1]> describe t1; #查看表结构,可简写为desc 表名+-------+-----------------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+-----------------------+------+-----+---------+-------+| id | int(11) | YES | | NULL | || name | varchar(50) | YES | | NULL | || sex | enum('male','female') | YES | | NULL | || age | int(3) | YES | | NULL | |+-------+-----------------------+------+-----+---------+-------+MariaDB [db1]> show create table t1G; #查看表详细结构,可加G 五,数据类型详见:https://www.cnblogs.com/peng104/p/9757047.html 六,表的完整性约束待更。。 七,修改表语法:1. 修改表名ALTER TABLE 表名RENAME 新表名;2. 增加字段ALTER TABLE 表名ADD 字段名 数据类型 [完整性约束条件…],ADD 字段名 数据类型 [完整性约束条件…];ALTER TABLE 表名ADD 字段名 数据类型 [完整性约束条件…] FIRST;ALTER TABLE 表名ADD 字段名 数据类型 [完整性约束条件…] AFTER 字段名;3. 删除字段ALTER TABLE 表名DROP 字段名;4. 修改字段ALTER TABLE 表名MODIFY 字段名 数据类型 [完整性约束条件…];ALTER TABLE 表名CHANGE 旧字段名 新字段名 旧数据类型 [完整性约束条件…];ALTER TABLE 表名CHANGE 旧字段名 新字段名 新数据类型 [完整性约束条件…];示例:1. 修改存储引擎mysql> alter table service-> engine=innodb;2. 添加字段mysql> alter table student10-> add name varchar(20) not null,-> add age int(3) not null default 22;mysql> alter table student10-> add stu_num varchar(10) not null after name; //添加name字段之后mysql> alter table student10-> add sex enum('male','female') default 'male' first; //添加到最前面3. 删除字段mysql> alter table student10-> drop sex;mysql> alter table service-> drop mac;4. 修改字段类型modifymysql> alter table student10-> modify age int(3);mysql> alter table student10-> modify id int(11) not null primary key auto_increment; //修改为主键5. 增加约束(针对已有的主键增加auto_increment)mysql> alter table student10 modify id int(11) not null primary key auto_increment;ERROR 1068 (42000): Multiple primary key definedmysql> alter table student10 modify id int(11) not null auto_increment;Query OK, 0 rows affected (0.01 sec)Records: 0 Duplicates: 0 Warnings: 06. 对已经存在的表增加复合主键mysql> alter table service2-> add primary key(host_ip,port);7. 增加主键mysql> alter table student1-> modify name varchar(10) not null primary key;8. 增加主键和自动增长mysql> alter table student1-> modify id int not null primary key auto_increment;9. 删除主键a. 删除自增约束mysql> alter table student10 modify id int(11) not null;b. 删除主键mysql> alter table student10-> drop primary key;示例 八,复制表复制表结构+记录 (key不会复制: 主键、外键和索引)mysql> create table new_service select * from service;只复制表结构mysql> select * from service where 1=2; //条件为假,查不到任何记录Empty set (0.00 sec)mysql> create table new1_service select * from service where 1=2;Query OK, 0 rows affected (0.00 sec)Records: 0 Duplicates: 0 Warnings: 0mysql> create table t4 like employees; 九,删除表DROP TABLE 表名;  总述:启动masqlmysql start mysql ;查看当前登陆的用户select user();查看所有的库show databases;退出当前客户端exit 或 q用户名root登陆mysql -uroot -p;放弃本条语句c设置密码set password = password("123");创建用户create user 'alex
MySQL主从复制
MySQL主从复制引入MySQL数据库的主从复制方案,是其自带的功能,并且主从复制并不是复制磁盘上的数据库文件,而是通过binlog日志复制到需要同步的从服务器上。MySQL数据库支持单向、双向、链式级联,等不同业务场景的复制。在复制的过程中,一台服务器充当主服务器(Master),接收来自用户的内容更新,而一个或多个其他的服务器充当从服务器(slave),接收来自Master上binlog文件的日志内容,解析出SQL,重新更新到Slave,使得主从服务器数据达到一致。主从复制的逻辑有以下几种一主一从,单向主从同步模式,只能在Master端写入数据一主多从应用场景# 利用复制功能当Master服务器出现问题时,我们可以人工的切换到从服务器继续提供服务,此时服务器的数据和宕机时的数据几乎完全一致。# 复制功能也可用作数据备份,但是如果人为的执行drop,delete等语句删除,那么从库的备份功能也就失效了.原理(1) master将改变记录到二进制日志(binary log)中(这些记录叫做二进制日志事件,binary log events);(2) slave将master的binary log events拷贝到它的中继日志(relay log);(3) slave重做中继日志中的事件,将改变反映它自己的数据。具体步骤1,配置master主库#查看数据库状态systemctl status mariadb#停mariadbsystemctl stop mariadb#修改配置文件, 各个系统存放mysq配置文件的位置可能不太一样vim /etc/my.cnf#修改内容#解释:server-id服务的唯一标识(主从之间都必须不同);log-bin启动二进制日志名称为mysql-bin[mysqld]server-id=1log-bin=mysql-bin#重启mariadbsystemctl start mariadb2,在主库添加进行同步的用户 # 1.新建用于主从同步的用户username,允许登录的从库是'%'create user 'username'@'%' identified by 'password';# 2.#注意:如果提示密码太简单不复合策略加在前面加这句mysql> set global validate_password_policy=0;# 3.给从库账号授权,说明给username从库复制的权限,在"%"机器上复制grant replication slave on *.* to 'username'@'%';#检查主库创建的复制账号select user,host from mysql.user;#检查授权账号的权限show grants for username@'%';# 实现对主数据库锁表只读,防止数据写入,数据复制失败flush table with read lock;# 4.检查主库的状态MariaDB [(none)]> show master status;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000001 | 575 | | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)# 注意:File是二进制日志文件名,Position 是日志开始的位置。后面从库会用到 后面从库会用到 后面从库会用到# 5.锁表后,一定要单独再打开一个SSH窗口,导出数据库的所有数据,[root@python]#mysqldump -uroot -p --all-databases > /data/all.sql# 6.确保数据导出后,没有数据插入,完毕再查看主库状态show master status;# 7.导出数据完毕后,解锁主库,恢复可写;unlock tables;# 8.将备份导出的数据scp至Slave数据库scp /data/all.sql root@ip:/data/3,配置salve从库机器# 1.设置server-id值并关闭binlog功能参数数据库的server-id在主从复制体系内是唯一的,Slave的server-id要与主库和其他从库不同,并且注释掉Slave的binlog参数。# 2.因此修改Slave的/etc/my.cnf,写入[mysqld]server-id=3# 3.重启数据库systemctl restart mariadb# 4.检查Slava从数据库的各项参数show variables like 'log_bin';show variables like 'server_id';# 5.恢复主库Master的数据导入到Slave库# 导入数据(注意sql文件的路径)mysql>source /data/all.sql;# 方法二:#mysql -uroot -p < abc.sql# 6.配置复制的参数,Slave从库连接Master主库的配置mysql > change master to master_host='x.x.x.x',master_user='username',master_password='password',master_log_file='mysql-bin.000001',master_log_pos=575;# 7.启动从库的同步开关,测试主从复制的情况start slave;# 8.查看复制状态show slave statusG;4,检测主从复制状态关键点MariaDB [(none)]> show slave statusG*************************** 1. row ***************************Slave_IO_State: Waiting for master to send eventMaster_Host: 192.168.11.133Master_User: pengMaster_Port: 3306Connect_Retry: 60Master_Log_File: mysql-bin.000001Read_Master_Log_Pos: 1039Relay_Log_File: slave-relay-bin.000002Relay_Log_Pos: 537Relay_Master_Log_File: mysql-bin.000001Slave_IO_Running: Yes # 为yes表示成功Slave_SQL_Running: Yes # 为yes表示成功注意:注意此处还未配置从库的只读模式,还需在slave服务器上配置/etc/my.cnf,加上以下配置,并且在slave上创建普通用户,使用普通用户主从同步即可达到只读的效果如果用root用户,无法达到readonly(只读模式),这是一个坑[mysqld]character-set-server=utf8collation-server=utf8_general_cilog-error=/var/log/mysqld.logserver-id=3read-only=true[client]default-character-set=utf8[mysql]default-character-set=utf8 
使用LNMP常见问题解答
一、LNMP的安装##先要下载,并根据不同系统进行安装:wget -c http://soft.vpser.net/lnmp/lnmp1.5.tar.gztar zxvf lnmp1.5.tar.gzcd lnmp1.5./install.sh #开始进行安装操作以上为下载及进入安装过程,以下为安装前简易设置,切记输入个其它域名及牢记mysql密码:+------------------------------------------------------------------------+| LNMP V1.5 for CentOS Linux Server, Written by Licess |+------------------------------------------------------------------------+| A tool to auto-compile & install LNMP/LNMPA/LAMP on Linux |+------------------------------------------------------------------------+| For more information please visit https://lnmp.org |+------------------------------------------------------------------------+You have 10 options for your DataBase install.1: Install MySQL 5.1.732: Install MySQL 5.5.60 (Default)3: Install MySQL 5.6.404: Install MySQL 5.7.225: Install MySQL 8.0.116: Install MariaDB 5.5.607: Install MariaDB 10.0.358: Install MariaDB 10.1.339: Install MariaDB 10.2.140: DO NOT Install MySQL/MariaDBEnter your choice (1, 2, 3, 4, 5, 6, 7, 8, 9 or 0): #选择mysql版本 默认为5.5.60No input,You will install MySQL 5.5.60===========================Please setup root password of MySQL.Please enter: vpsmm.com #输入mysql的密码===========================Do you want to enable or disable the InnoDB Storage Engine?Default enable,Enter your choice [Y/n]: n #是否安装InnoDB环境 默认不需要 whmcs之类特殊程序需求You will disable the InnoDB Storage Engine!===========================You have 8 options for your PHP install.1: Install PHP 5.2.172: Install PHP 5.3.293: Install PHP 5.4.454: Install PHP 5.5.385: Install PHP 5.6.36 (Default)6: Install PHP 7.0.307: Install PHP 7.1.188: Install PHP 7.2.6Enter your choice (1, 2, 3, 4, 5, 6, 7 or 8): 8 #默认php版本 这里选择最新You will install PHP 7.2.6===========================You have 3 options for your Memory Allocator install.1: Don't install Memory Allocator. (Default)2: Install Jemalloc3: Install TCMallocEnter your choice (1, 2 or 3): 1 这个默认选择不安装即可You will install not install Memory Allocator.#按任意键,设置完成,正式进入安装,预计20-40分钟完成常见lnmp管理命令:#1.2版本以后,不需要再执行/root/lnmp了,可以在任意位置执行lnmp命令lnmp #会出现一些提示信息lnmp restart #重启lnmp vhost add #添加网站绑定lnmp database add #添加数据库信息二,域名绑定详解其实所谓的域名绑定,就是通过命令的形式,简易创建一个conf文件到/usr/local/nginx/conf/vhost下面,这个过程完全可以手工创建conf,或者,平时修改目录、域名等,直接修改conf文件,效果完全一样:lnmp vhost add #执行lnmp添加网站命令+-------------------------------------------+| Manager for LNMP, Written by Licess |+-------------------------------------------+Please enter domain(example: www.lnmp.org): vpsmm.com #输入绑定的主域名======================================Your domain: vpsmm.com======================================Do you want to add more domain name? (y/n) y #是否绑定其它域名Enter domain name(example: lnmp.org *.lnmp.org): www.vpsmm.com #输入其它域名domain list: www.vpsmm.comPlease enter the directory for the domain: vpsmm.com(Default directory: /home/wwwroot/vpsmm.com): #默认创建的网站文件所在目录Virtual Host Directory: /home/wwwroot/vpsmm.com===========================Allow Rewrite rule? (y/n)===========================y #是否添加伪静态文件Please enter the rewrite of programme:wordpress,discuz,typecho,sablog,dabr rewrite was exist.(Default rewrite: other):typecho #小夜用的typecho程序===========================You choose rewrite=typecho======================================================Allow access_log? (y/n)===========================n #是否启用日志文件======================================================Create database and MySQL user with same name (y/n)======================================================y #是否创建mysql数据库verify your current MySQL root password: **** #输入安装时的mysql数据库root密码Warning: Using a password on the command line interface can be insecure.MySQL root password correct.Enter database name: vpsmm_user #创建数据库用户名Your will create a database and MySQL user with same name: vpsmm_userPlease enter password for mysql user vpsmm_user: vpsmmpasswdYour password: vpsmmpasswd #创建相应密码Press any key to start create virtul host...Create Virtul Host directory......set permissions of Virtual Host directory......You select the exist rewrite rule:/usr/local/nginx/conf/typecho.confGracefully shutting down php-fpm . doneStarting php-fpm doneTest Nginx configure file......nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is oknginx: configuration file /usr/local/nginx/conf/nginx.conf test is successfulRestart Nginx......Warning: Using a password on the command line interface can be insecure.Warning: Using a password on the command line interface can be insecure.User vpsmm_user create Sucessfully.Warning: Using a password on the command line interface can be insecure.Warning: Using a password on the command line interface can be insecure.Warning: Using a password on the command line interface can be insecure.Database: vpsmm_user create Sucessfully.Warning: Using a password on the command line interface can be insecure.Warning: Using a password on the command line interface can be insecure.GRANT ALL PRIVILEGES ON vpsmm_user Sucessfully.Warning: Using a password on the command line interface can be insecure.FLUSH PRIVILEGES Sucessfully.================================================Virtualhost infomation:Your
Go 语言,开源服务端代码自动生成 框架 - EasyGoServer
EasyGoServer作者:林冠宏 / 指尖下的幽灵掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8博客:http://www.cnblogs.com/linguanh/GitHub : https://github.com/af913337456/联系方式 / Contact:[email protected] 概述---- 脚本介绍-------- Linux-------- Windows-------- Mac---- 使用流程---- 部分代码说明---- 开源地址概述一个能够仅仅依赖你创建好的 sql 文件,就能 自动帮你生成基础服务端框架代码 的 go server 框架。包含有:1,基础的 增删改查2,拓展性强的API3,客户端的数据传入 与 服务端的输出 全部依赖 struct例如你的一个输入结构体 inputStruct 设置为type inputStruct struct {Id int64 `json:"id" nullTag:"1"` // nullTag==1 指明 id 必须要求在客户端传入 {"id":123}Name string `json:"name" nullTag:"0"` // ==0 指明 name 在客户端输入的时候可以不必要}对应上例,客户端输入的 json : {"id":666, "name":"lgh"}当你在使用 select 的时候,你的 sql 如果是这样的:select User.id , User.age from User那么你的对应输出结构体 outputStruct 应该是:type inputStruct struct {Id int64 `json:"id"`Age int64 `json:"age"`}4,真正需要你写的代码极少,例如第三点的例子,你要写的就那么多,其中默认的 struct 会自动帮你生成脚本介绍根据 sql 文件,自动生成代码文件,包含有 struct.go,每张表对应生成一个包含有增删改查的基础方法文件one_key_create_code根据内置的 makefile 或者 .bat 编译并运行默认的 go server 程序,注意是默认的make_serverLinuxone_key_create_code.shmake_server.shMakefileWindowsone_key_create_code.batmake_server.batMac参照 linux 的使用流程1,在你的 服务器 安装 mysql 或者 mariadb2,编写好的你的 sql 文件,可以参照我源码里面的 this.sql3,运行步骤2编写好的 sql 文件4,修改 sql_2_api.go 里面 main 内的 sql 文件名称5,运行 one_key_create_code 脚本,成功后会在同级目录生成下面文件,记得刷新目录struct.go,里面包含注释规范对应你 sql 文件里面的表名称生成的函数文件,格式:func_表名称.go6,自己写好,main.go 或者 使用我提供的默认 LghSampleMain.go,在里面 添加你自己的路由router.HandleFunc("/insert",insert_luser_sample).Methods("POST")router.HandleFunc("/select",select_luser_sample).Methods("GET")router.HandleFunc("/update",update_luser_sample).Methods("POST")router.HandleFunc("/delete",delete_luser_sample).Methods("POST")7,配置好 conf.json 文件,我里面有例子// Host 是绝对路径// Port 是要被监听的端口{"Host": "127.0.0.1","Port": ":8884","FilePort":":8885","DbName":"database","DbUser":"root","DbPw":"123456","DbPort":"3306"}8,现在执行 make_server 脚本,观察控制台的输出,即可。部分代码说明核心的参数结构体type LghRequest struct {w http.ResponseWriterr *http.Request// 标记使用,当前的方法名称funcName string// 输入的结构体,与客户端输入的 json 成对应关系inputStruct interface{}// 自定义 slices 的回调,方便你做参数处理,返回 true 意味着此次操作终止,例如 updateslicesCallBack func(slices []interface{}) bool// 根据传入的 jsonObj 生成的 slices 来回调,方法生成自定义 sqlgetSqlCallBack func(slices []interface{},inputStruct interface{}) string}例子方法1,演示不需要参数的形式/** 演示不需要参数的形式 */func update_0(w http.ResponseWriter,r *http.Request) {request := LghRequest{w,r,"update_luser",nil, /** nil 表示没输入结构体 */func(slices *[]interface{}) bool{return false},func(slices *[]interface{},inputStruct interface{}) string {return "update LUser set u_user_id='444' where id='1'"}}updateDataByStruct(request)}2,演示当有参数输入的时候,参数仅做判断,但是不需要组合到 sql 的情况/** 演示当有参数输入的时候,参数仅做判断,但是不需要组合到 sql的情况 */func update_1(w http.ResponseWriter,r *http.Request) {type testS struct {Id int64 `json:"id" nullTag:"1"` // nullTag==1 指明 id 必须要求在客户端传入 {"id":123}}request := LghRequest{w,r,"update_luser",new (testS),func(slices []interface{}) bool{// 在这里对 slices 做你想做的操作,增加或者删除等等if slices[0] == -1{return true /** 返回 true,终止插入,提示错误或者其它 */}slices = append(slices[:0], nil) /** 自己做完处理删除掉 */return false},func(slices []interface{},inputStruct interface{}) string {// 如果你想根据输入的 json 数据来特定生成 sql,那么就可以在这里使用 slices 来操作return "update LUser set u_user_id='444' where id='2'"}}updateDataByStruct(request)}3,演示使用输入参数的情况/** 演示使用输入参数的情况 */func update_luser_sample(w http.ResponseWriter,r *http.Request) {type testS struct {Id int64 `json:"id" nullTag:"1"`}request := LghRequest{w,r,"update_luser",new (testS),func(slices []interface{}) bool{return false},func(slices []interface{},inputStruct interface{}) string {return "update LUser set u_user_id='444' where id=?" /** 对应 id */}}updateDataByStruct(request)}开源地址https://github.com/af913337456/EasyGoServer