Liunx中shell操作Mysql数据库

tech2024-06-16  55

日常工作中,我们需要对mysql数据库进行查询和修改,如果遇到多数据库,多表时,在mysql的提示符下运行mysql会非常麻烦,为了解决这个问题,我们可以在shell中操作mysql的方法。

shell命令行非交互式的操作数据库的方法:

mysql -hhostname -Pport -uusername -ppassword -e sql语句

#!/bin/bash HOSTNAME="127.0.0.1" #数据库信息 PORT="3306" USERNAME="root" PASSWORD="root" DBNAME="test_db_test" #数据库名称 TABLENAME="test_table_test" #数据库中表的名称 #创建数据库 create_db_sql="create database IF NOT EXISTS ${DBNAME}" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} -e "${create_db_sql}" #创建表 create_table_sql="create table IF NOT EXISTS ${TABLENAME} ( name varchar(20), id int(11) default 0 )" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${create_table_sql}" #插入数据 insert_sql="insert into ${TABLENAME} values('billchen',2)" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${insert_sql}" #查询 select_sql="select * from ${TABLENAME}" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}" #更新数据 update_sql="update ${TABLENAME} set id=3" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${update_sql}" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}" #添加字段 alter_sql="ALTER TABLE table_name ADD field_name field_type" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${alter_sql}" #删除数据 mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${delete_sql}" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}"

当我们有多个数据库或者多个表时就可以采用for循环的方式进行操作,

DBNAME_list="db1 db2 db3" for DBNAME in ${DBNAME_list} do update_sql="update ${TABLENAME} set id=3" mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} ${DBNAME} -e "${select_sql}" done
最新回复(0)