下午寫了一個簡單的 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";
}
?>