MySQL LOAD DATA常用用法
一般想要文件灌入数据库会用LOAD DATA语句,这里提供一个比较common的用法,导入文件内容到数据库,分为两个步骤:
1. 导入数据到备份表_bak,这样可以保证load大数据量时万一有错误,原表仍然不受影响
2. 重命名表 原表名-> _tmp, _bak -> 原表名, _tmp -> _bak,相当于做了一次交换。
具体SQL参考如下:
步骤1:
${MYSQL_CLIENT} -u"${BEIDOU_DB_USER_SITEURL}" -p"${BEIDOU_DB_PASSWORD_SITEURL}" -h"${BEIDOU_DB_IP_SITEURL}" -P"${BEIDOU_DB_PORT_SITEURL}" –default-character-set=utf8 -e "
use beidouurl;
drop table if exists ${BLACKLIST_TABLE}_bak;
create table ${BLACKLIST_TABLE}_bak like ${BLACKLIST_TABLE};
load data local infile ‘${VISITOR_BLACKLIST_DATA_PATH}/${BLACKLIST_FILE}’ into table ${BLACKLIST_TABLE}_bak CHARACTER SET gbk (${BLACKLIST_TABLE_COLUMN});
" 1>> ${LOG_FILE} 2>>${LOG_FILE}.wf
步骤2:
${MYSQL_CLIENT} -u"${BEIDOU_DB_USER_SITEURL}" -p"${BEIDOU_DB_PASSWORD_SITEURL}" -h"${BEIDOU_DB_IP_SITEURL}" -P"${BEIDOU_DB_PORT_SITEURL}" –default-character-set=utf8 -e "
use beidouurl;
rename table ${BLACKLIST_TABLE} to ${BLACKLIST_TABLE}_tmp,
${BLACKLIST_TABLE}_bak to ${BLACKLIST_TABLE},
${BLACKLIST_TABLE}_tmp to ${BLACKLIST_TABLE}_bak;
" 1>> ${LOG_FILE} 2>>${LOG_FILE}.wf
附:LOAD DATA格式
LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE ‘file_name’
[REPLACE | IGNORE]
INTO TABLE tbl_name
[CHARACTER SET charset_name]
[{FIELDS | COLUMNS}
[TERMINATED BY ‘string’]
[[OPTIONALLY] ENCLOSED BY ‘char’]
[ESCAPED BY ‘char’]
]
[LINES
[STARTING BY ‘string’]
[TERMINATED BY ‘string’]
]
[IGNORE number LINES]
[(col_name_or_user_var,…)]
[SET col_name = expr,…]