首页主机资讯CentOS Python如何连接数据库

CentOS Python如何连接数据库

时间2025-10-13 21:02:03发布访客分类主机资讯浏览472
导读:在CentOS上使用Python连接数据库,通常需要使用数据库的官方Python驱动程序。以下是一些常见数据库及其对应的Python连接方法: 1. MySQL 安装MySQL客户端库: sudo yum install mysql-dev...

在CentOS上使用Python连接数据库,通常需要使用数据库的官方Python驱动程序。以下是一些常见数据库及其对应的Python连接方法:

1. MySQL

安装MySQL客户端库

sudo yum install mysql-devel

安装Python的MySQL驱动

pip install mysql-connector-python

示例代码

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM customers"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

2. PostgreSQL

安装PostgreSQL客户端库

sudo yum install postgresql-devel

安装Python的PostgreSQL驱动

pip install psycopg2-binary

示例代码

import psycopg2

conn = psycopg2.connect(
    dbname="yourdatabase",
    user="yourusername",
    password="yourpassword",
    host="localhost"
)

cur = conn.cursor()

cur.execute("SELECT * FROM customers")

rows = cur.fetchall()

for row in rows:
    print(row)

3. SQLite

SQLite是一个嵌入式数据库,不需要单独安装客户端库。

安装Python的SQLite驱动(通常已经内置):

pip install pysqlite3

示例代码

import sqlite3

conn = sqlite3.connect('example.db')

cursor = conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
                 (date text, trans text, symbol text, qty real, price real)''')

cursor.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

conn.commit()

cursor.execute("SELECT * FROM stocks")

for row in cursor.fetchall():
    print(row)

conn.close()

4. MongoDB

安装MongoDB客户端库

sudo yum install mongodb-org
sudo systemctl start mongod
sudo systemctl enable mongod

pip install pymongo

示例代码

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

db = client['yourdatabase']

collection = db['customers']

# 插入文档
post = {
"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
    

post_id = collection.insert_one(post).inserted_id

# 查询文档
for post in collection.find():
    print(post)

注意事项

  1. 权限和安全性:确保数据库用户有适当的权限,并且密码安全。
  2. 网络配置:如果数据库不在本地,确保防火墙允许相应的端口通信。
  3. 依赖管理:使用虚拟环境(如virtualenvconda)来管理项目依赖,避免全局安装导致的冲突。

通过以上步骤,你可以在CentOS上使用Python连接到不同的数据库。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: CentOS Python如何连接数据库
本文地址: https://pptw.com/jishu/725115.html
CentOS LibOffice的安全性如何 CentOS Python如何部署Web应用

游客 回复需填写必要信息