用 shell 指令碼訪問 mysql 資料庫

來源:互聯網
上載者:User

原文連結:http://www.vpsee.com/2009/08/use-shell-script-to-access-mysql/

下午寫了一個簡單的 bash 指令碼,用來測試程式,輸入一個測試案例檔案,

輸出沒有通過測試的用例和結果,然後把結果儲存到資料庫裡。如何在 bash 指令碼裡直接存取資料庫呢?

既然在 shell 裡可以直接用 mysql 命令操作資料庫,那麼在 shell script 裡也應該可以通過調用 mysql 來操作資料庫。

比如用下面的 bash shell 指令碼查詢資料庫:

Bash


如果需要複雜的資料庫操作的話不建議用 shell 指令碼,用 Perl/Python/PHP 操作資料庫很方便,

分別通過 Perl DBI/Python MySQLdb/PHP MySQL Module 介面來操作資料庫。

這裡再給出這三種不同語言串連、查詢資料庫的簡單例子(為了簡單和減少篇幅刪除一些不必要的代碼):

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";
}


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])


<?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";
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.