MySQL 如何使用shell脚本访问mysql数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5809064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access mysql database using shell script?
提问by Bhushan
Is there a way I can access MySQL database using shell script? want to do some selects and some inserts on multiple tables?
有没有办法使用 shell 脚本访问 MySQL 数据库?想在多个表上做一些选择和一些插入吗?
It will be great if you can give some sample code as I am new to scripting.
如果您能提供一些示例代码,那就太好了,因为我是脚本编写新手。
采纳答案by Lactose
This link seems to have the information you want.
这个链接似乎有你想要的信息。
http://www.cyberciti.biz/faq/using-mysql-in-shell-scripts/
http://www.cyberciti.biz/faq/using-mysql-in-shell-scripts/
mysql -u user -p dbnane
回答by ishimwe
try this
尝试这个
#!/bin/bash
echo "show all tables"
mysql -uroot -p'password' dbname<<EOFMYSQL
show tables;
EOFMYSQL
echo "Count of all records"
mysql -uroot -p'password' dbname<<EOFMYSQL
select count(*) from tbname;
EOFMYSQL
回答by Pascal MARTIN
You can use the mysql
command-line tool, from your shell-script.
您可以使用shell 脚本中的mysql
命令行工具。
回答by Bhushan
Actually, I achieved it using Perl. I wrote a Perl script which was able to access the MySQL database.
实际上,我是使用 Perl 实现的。我编写了一个能够访问 MySQL 数据库的 Perl 脚本。
All I had to do was include this in my Perl script:
我所要做的就是将它包含在我的 Perl 脚本中:
# PERL MODULES USING
use DBI;
use DBD::mysql;
But just make sure that these modules are properly installed. I don't know how to do it since my System Administrator did it for me.
但只要确保这些模块安装正确。我不知道该怎么做,因为我的系统管理员为我做了。
You can access db like this:
您可以像这样访问数据库:
# MYSQL CONFIG VARIABLES
$platform = "mysql";
$host = "<your db server ip>";
$database = "<db name>";
$org_table = "<table name>";
$user = "<username>";
$pw = "<password>";
# DATA SOURCE NAME
$dsn = "dbi:$platform:$database:$host:$port";
# PERL DBI CONNECT
$connect = DBI->connect($dsn, $user, $pw);
Now suppose you create a query string, then you want to execute it:
现在假设您创建了一个查询字符串,然后您想执行它:
#SELECT THE ORG SHORT NAMES
$select_org = "SELECT id, short_name FROM $org_table";
$org_handle = $connect->prepare($select_org);
$org_handle will have the resultset.
回答by Jayhello
For example, select all the name
field in table tablename
of database dbname
and redirect all name to /tmp/all_name.txt.
例如,选择of中的所有name
字段并将所有名称重定向到/tmp/all_name.txt。table tablename
database dbname
#!/bin/sh
mysql -uuser_name -puser_pwd -h10.10.10.10 -A --default-character-set=utf8 \
-e "select name from dbname.tablename;" > /tmp/all_name.txt
Note, -uuser_name
not -u user_name
, -puser_pwd not -p user_pwd
注意,-uuser_name
不是-u user_name
, -puser_pwd not -p user_pwd