Mysql

数据库操作

批量 kill 掉查询

有时候需要批量 kill 掉查询进程,有几种方式,比如生成 sql 文件执行:

  1. mysql> select concat('KILL ',id,';') from information_schema.processlist
  2. where user='root' and time > 200 into outfile '/tmp/a.txt';
  3. mysql> source /tmp/a.txt;

有时候没法生成文件(权限原因),可以直接生成 sql 语句 copy 下来复制到命令行也可以,或者连接成一行方便复制:

  1. mysql > select concat('KILL ',id,';') from information_schema.processlist where db='dbname';`
  2. mysql > select GROUP_CONCAT(stat SEPARATOR ' ') from (select concat('KILL ',id,';') as stat from information_schema.processlist where db='dbname') as stats;
  3. # 按客户端 IP 分组,看哪个客户端的链接数最多
  4. select client_ip,count(client_ip) as client_num from (select substring_index(host,':' ,1) as client_ip from processlist ) as connect_info group by client_ip order by client_num desc;
  5. # 查看正在执行的线程,并按 Time 倒排序,看看有没有执行时间特别长的线程
  6. select * from information_schema.processlist where Command != 'Sleep' order by Time desc;
  7. # 找出所有执行时间超过 5 分钟的线程,拼凑出 kill 语句,方便后面查杀
  8. select concat('kill ', id, ';') from information_schema.processlist where Command != 'Sleep' and Time > 300 order by Time desc;

也可以通过 python 脚本来完成,原理也是查询进程 id 然后删除:

  1. # https://stackoverflow.com/questions/1903838/how-do-i-kill-all-the-processes-in-mysql-show-processlist
  2. import pymysql # pip install pymysql
  3. connection = pymysql.connect(host='',
  4. user='',
  5. db='',
  6. password='',
  7. cursorclass=pymysql.cursors.DictCursor)
  8. with connection.cursor() as cursor:
  9. cursor.execute('SHOW PROCESSLIST')
  10. for item in cursor.fetchall():
  11. if item.get('db') == 'dbname': # 过滤条件
  12. _id = item.get('Id')
  13. print('kill %s' % item)
  14. cursor.execute('kill %s', _id)
  15. connection.close()

删除大表(借助一个临时表)

  1. # https://stackoverflow.com/questions/879327/quickest-way-to-delete-enormous-mysql-table
  2. CREATE TABLE new_foo LIKE foo;
  3. RENAME TABLE foo TO old_foo, new_foo TO foo;
  4. DROP TABLE old_foo;

统计表的大小并排序

  1. # https://stackoverflow.com/questions/9620198/how-to-get-the-sizes-of-the-tables-of-a-mysql-database
  2. SELECT
  3. table_schema as `Database`,
  4. table_name AS `Table`,
  5. round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
  6. FROM information_schema.TABLES
  7. ORDER BY (data_length + index_length) DESC;

查看表信息

  1. mysql > show table status;
  2. mysql > show table status where Rows>100000;

纵向显示

有时候表字段比较多的时候,查询结果显示会很乱,可以使用竖屏显示的方式,结尾加上 \G

  1. mysql > select * from user limit 10 \G

导出和导入表的数据

  1. shell > mysqldump -u user -h host -p pass db_name table_name > out.sql
  2. mysql > source /path/to/out.sql

Python Mysql 操作

Sqlalchemy 示例

  1. # -*- coding: utf-8 -*-
  2. """
  3. sqlalchemy 快速读取 mysql 数据示例
  4. pip install SQLAlchemy -i https://pypi.doubanio.com/simple --user
  5. pip install pymysql -i https://pypi.doubanio.com/simple --user
  6. """
  7. import sqlalchemy as db
  8. """
  9. # 本机 mysql 创建一个测试表
  10. CREATE TABLE `area_code` (
  11. `id` int(11) NOT NULL AUTO_INCREMENT,
  12. `code` bigint(12) NOT NULL DEFAULT '0' COMMENT '行政区划代码',
  13. `name` varchar(32) NOT NULL DEFAULT '' COMMENT '名称',
  14. PRIMARY KEY (`id`),
  15. KEY `idx_code` (`code`)
  16. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  17. """
  18. def sqlalchemy_demo():
  19. # https://towardsdatascience.com/sqlalchemy-python-tutorial-79a577141a91
  20. url = "mysql+pymysql://root:wnnwnn@127.0.0.1:3306/testdb" # 测试地址
  21. engine = db.create_engine(url)
  22. connection = engine.connect()
  23. metadata = db.MetaData()
  24. table = db.Table('area_code', metadata, autoload=True, autoload_with=engine)
  25. # 插入单个数据
  26. query = db.insert(table).values(code=10010, name="北京")
  27. connection.execute(query)
  28. # 插入多个数据
  29. query = db.insert(table)
  30. values = [
  31. {'code': 10020, 'name': '上海'},
  32. {'code': 10030, 'name': '杭州'},
  33. ]
  34. connection.execute(query, values)
  35. # 查询
  36. query = db.select([table]).order_by(db.desc(table.columns.id)).limit(10)
  37. rows = connection.execute(query).fetchall()
  38. for row in rows:
  39. print(row.id, row.code, row.name)
  40. # 修改
  41. query = db.update(table).values(name="帝都").where(table.columns.code == 10010)
  42. connection.execute(query)
  43. # 删除行
  44. query = db.delete(table).where(table.columns.code == 10010)
  45. connection.execute(query)
  46. if __name__ == "__main__":
  47. sqlalchemy_demo()

Go Mysql 操作

go 可以使用 gorm 或者 database/sql

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "time"
  7. _ "github.com/go-sql-driver/mysql"
  8. )
  9. func main() {
  10. db, err := sql.Open("mysql", "root:root@(127.0.0.1:3306)/root?parseTime=true")
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. if err := db.Ping(); err != nil {
  15. log.Fatal(err)
  16. }
  17. { // Create a new table
  18. query := `
  19. CREATE TABLE users (
  20. id INT AUTO_INCREMENT,
  21. username TEXT NOT NULL,
  22. password TEXT NOT NULL,
  23. created_at DATETIME,
  24. PRIMARY KEY (id)
  25. );`
  26. if _, err := db.Exec(query); err != nil {
  27. log.Fatal(err)
  28. }
  29. }
  30. { // Insert a new user
  31. username := "johndoe"
  32. password := "secret"
  33. createdAt := time.Now()
  34. result, err := db.Exec(`INSERT INTO users (username, password, created_at) VALUES (?, ?, ?)`, username, password, createdAt)
  35. if err != nil {
  36. log.Fatal(err)
  37. }
  38. id, err := result.LastInsertId()
  39. fmt.Println(id)
  40. }
  41. { // Query a single user
  42. var (
  43. id int
  44. username string
  45. password string
  46. createdAt time.Time
  47. )
  48. query := "SELECT id, username, password, created_at FROM users WHERE id = ?"
  49. if err := db.QueryRow(query, 1).Scan(&id, &username, &password, &createdAt); err != nil {
  50. log.Fatal(err)
  51. }
  52. fmt.Println(id, username, password, createdAt)
  53. }
  54. { // Query all users
  55. type user struct {
  56. id int
  57. username string
  58. password string
  59. createdAt time.Time
  60. }
  61. rows, err := db.Query(`SELECT id, username, password, created_at FROM users`)
  62. if err != nil {
  63. log.Fatal(err)
  64. }
  65. defer rows.Close()
  66. var users []user
  67. for rows.Next() {
  68. var u user
  69. err := rows.Scan(&u.id, &u.username, &u.password, &u.createdAt)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. users = append(users, u)
  74. }
  75. if err := rows.Err(); err != nil {
  76. log.Fatal(err)
  77. }
  78. fmt.Printf("%#v", users)
  79. }
  80. {
  81. _, err := db.Exec(`DELETE FROM users WHERE id = ?`, 1)
  82. if err != nil {
  83. log.Fatal(err)
  84. }
  85. }
  86. }