shell腳本連接操作mysql

shell腳本鏈接mysql模板如下:

mysql -h$hostname -P$port -u$username -p$password << EOF
use $database;

XXXXsql語句

commit;
EOF

 

增刪改查舉例如下:

#!/bin/bash

hostname="ip"
port="3306"
username="aabb"
password="aabb"
database="aa"
tablename="aa_test_shell"

//創建表

mysql -h$hostname -P$port -u$username -p$password << EOF
use $database;
create table IF NOT EXISTS $tablename (unit varchar(10) NOT NULL COMMENT '日期格式YYYY-MM-DD', prov_name varchar(32) NOT NULL COMMENT '省份名',
prov_id varchar(32) NOT NULL COMMENT '省份id',region_type int(2) NOT NULL COMMENT '地區類型:0全國,1省,2市,3區縣',time_type int(2) NOT NULL COMMENT '12345,年季月日周');
commit;
EOF
if [ $? -eq 0 ]
then 
  echo "create table success !"
fi

//插入

mysql -h$hostname -P$port -u$username -p$password << EOF
use $database;
INSERT INTO aa_test_shell (unit, prov_name, prov_id, region_type, time_type) VALUES ('test', 'test','test', 1, 2);
INSERT INTO aa_test_shell (unit, prov_name, prov_id, region_type, time_type) VALUES ('test1', 'tes1t','test1', 11, 12);
commit;
EOF
if [ $? -eq 0 ]
then
  echo "insert  success !"
fi

//刪除

mysql -h$hostname -P$port -u$username -p$password << EOF
use $database;
delete from aa_test_shell where unit='test';
commit;
EOF
if [ $? -eq 0 ]
then
  echo "delete  success !"
fi

//更新

mysql -h$hostname -P$port -u$username -p$password << EOF
use $database;
update aa_test_shell set region_type=100 where unit='test1';
commit;
EOF
if [ $? -eq 0 ]
then
  echo "update  success !"
fi

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章