python:
# 需要先安装mysqlclient数据包:
# pip install mysqlclient -i https://pypi.tuna.tsinghua.edu.cn/simple
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect('localhost',user = "root",passwd = "root",db = "test", charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT pname, age from zzt")
results = cursor.fetchall()
for row in results:
age = row[1]
name = row[0]
# 打印结果
print("fname=%s,age=%s" % (name, age))
# 关闭数据库连接
db.close()
php
这是一个演示数据库连接和查询的程序<br>
数据库:test, 表:zzt, 查询语句:列出所有内容<br><br>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
echo "数据库连接成功<br>";
$sql = "SELECT age, pname FROM zzt";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "name: " . $row["pname"]. " age: " . $row["age"]."<br>";
}
} else {
echo "0 结果";
}
?>