下午写了一个简单的 bash 脚本,用来测试程序,输入一个测试用例文件,输出没有通过测试的用例和结果,然后把结果保存到数据库里。如何在 bash 脚本里直接访问数据库呢?既然在 shell 里可以直接用 mysql 命令操作数据库,那么在 shell script 里也应该可以通过调用 mysql 来操作数据库。比如用下面的 bash shell 脚本查询数据库:
#!/bin/bash
mysql -uvpsee -ppassword test EOFMYSQL
select * from test_mark;
EOFMYSQL
#!/usr/bin/perl
use DBI;
$db = DBI->connect('dbi:mysql:test', 'vpsee', 'password');
$query = "select * from test_mark";
$cursor = $db->prepare($query);
$cursor->execute;
while (@row = $cursor->fetchrow_array) {
print "@row\n";
}
#!/usr/bin/python
import MySQLdb
db = MySQLdb.Connect("localhost", "vpsee", "password", "test")
cursor = db.cursor()
query = "SELECT * FROM test_mark"
cursor.execute(query)
while (1):
row = cursor.fetchone()
if row == None:
break
print "%s, %s, %s, %s" % (row[0], row[1], row[2], row[3])
#!/usr/bin/php
?php
$db = mysql_connect("localhost", "vpsee", "password");
mysql_select_db("test");
$result = mysql_query("SELECT * FROM test_mark");
while ($row = mysql_fetch_array($result)) {
print "$row[0] $row[1] $row[2] $row[3]\n";
}
?>