Shell, Perl, Python, PHP access to MySQL database code instance _linux Shell

Source: Internet
Author: User
Tags mysql commands php mysql

A simple bash script was written in the afternoon to test the program, enter a test case file, output the use cases and results that did not pass the test, and then save the results to the database. How do I directly access a database in a bash script? Since you can manipulate the database directly in the shell with MySQL commands, you should also be able to manipulate the database in shell script by invoking MySQL. For example, use the following bash shell script to query the database:

Bash

Copy Code code as follows:

#!/bin/bash

Mysql-uvpsee-ppassword Test << Eofmysql
SELECT * from Test_mark;
Eofmysql


If you need a complex database operation, it is not recommended to use Shell script, the perl/python/php operation of the database is very convenient, respectively, through the Perl dbi/python mysqldb/php MySQL Module interface to operate the database. Here are a few simple examples of these three different language connections and query databases (to remove unnecessary code for simplicity and reduced space):

Perl

Copy Code code as follows:

#!/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";
}


Python
Copy Code code as follows:

#!/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])


PHP
Copy Code code as follows:

#!/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];
}
?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.