您现在的位置是:网站首页> 编程资料编程资料
Shell、Perl、Python、PHP访问 MySQL 数据库代码实例_linux shell_
2023-05-26
343人已围观
简介 Shell、Perl、Python、PHP访问 MySQL 数据库代码实例_linux shell_
下午写了一个简单的 bash 脚本,用来测试程序,输入一个测试用例文件,输出没有通过测试的用例和结果,然后把结果保存到数据库里。如何在 bash 脚本里直接访问数据库呢?既然在 shell 里可以直接用 mysql 命令操作数据库,那么在 shell script 里也应该可以通过调用 mysql 来操作数据库。比如用下面的 bash shell 脚本查询数据库:
Bash
#!/bin/bash
mysql -uvpsee -ppassword test << EOFMYSQL
select * from test_mark;
EOFMYSQL
如果需要复杂的数据库操作的话不建议用 shell 脚本,用 Perl/Python/PHP 操作数据库很方便,分别通过 Perl DBI/Python MySQLdb/PHP MySQL Module 接口来操作数据库。这里再给出这三种不同语言连接、查询数据库的简单例子(为了简单和减少篇幅删除一些不必要的代码):
Perl
#!/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
#!/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
#!/usr/bin/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";
}
?>
- Python3.7 pyodbc完美配置访问access数据库
- 详解js文件通过python访问数据库方法
- 对Python通过pypyodbc访问Access数据库的方法详解
- Python使用pyodbc访问数据库操作方法详解
- Python轻量级ORM框架Peewee访问sqlite数据库的方法详解
- Python的Tornado框架实现异步非阻塞访问数据库的示例
- Linux下通过python访问MySQL、Oracle、SQL Server数据库的方法
- python访问mysql数据库的实现方法(2则示例)
- python使用MySQLdb访问mysql数据库的方法
- Python访问纯真IP数据库脚本分享
- 在Linux中通过Python脚本访问mdb数据库的方法
- python访问纯真IP数据库的代码
- 使用Python通过oBIX协议访问Niagara数据的示例
相关内容
- Bash脚本内置的调试方法技巧_linux shell_
- Shell脚本配合iptables屏蔽来自某个国家的IP访问_linux shell_
- Shell脚本逐行读取文本文件(不改变文本格式)_linux shell_
- Shell脚本一次读取文件中一行的2种写法_linux shell_
- Shell中的${}、##和%%使用范例_linux shell_
- ssh远程执行命令方法和Shell脚本实例_linux shell_
- shell 1>&2 2>&1 &>filename重定向的含义和区别_linux shell_
- linux Shell入门:掌握Linux,OS X,Unix的Shell环境_linux shell_
- 分享20个Unix/Linux 命令技巧_linux shell_
- linux下使用ssh远程执行命令批量导出数据库到本地_linux shell_
