shell腳本操做mysql數據庫,使用mysql的-e參數能夠執行各類sql的(建立,刪除,增,刪,改、查)等各類操做
shell腳本操做mysql數據庫,使用mysql的-e參數能夠執行各類sql的(建立,刪除,增,刪,改、查)等各類操做
mysql -hhostname -Pport -uusername -ppassword -e 相關mysql的sql語句,不用在mysql的提示符下運行mysql,便可以在shell中操做mysql的方法。
#!/bin/bash
HOSTNAME="192.168.111.84" #數據庫信息
PORT="3306"
USERNAME="root"
PASSWORD=""
DBNAME="test_db_test" #數據庫名稱
TABLENAME="test_table_test" #數據庫中表的名稱
#建立數據庫
create_db_sql="create database ${DBNAME} IF NOT EXISTS ${DBNAME}"
mysql -h${HOSTNAME} -P${PORT} -u${USERNAME} -p${PASSWORD} -e "${create_db_sql}"
#建立表
create_table_sql="create table ${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}"
#刪除數據
delete_sql="delete from ${TABLENAME}"
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}"
--------------------------------------------
<?php
$sql = '"CREATE TABLE `test`.`params` (`id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,`section` varchar(30) NOT NULL,`param` varchar(30) NOT NULL,`value` varchar(50) NOT NULL)"';
$cmdArr = array(
'd:\\xampp\\mysql\\bin\\mysql -uroot -pa12345 -e ' . $sql
);
$tmpArr = array();
foreach($cmdArr as $cmd){
exec($cmd,$tmpArr,$return);
var_export($tmpArr);
echo $return;
}php