Ubuntu下Python数据库连接如何操作
导读:在Ubuntu下使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接操作: MySQL 首先,安装MySQL数据库和Python的MySQL驱动: sudo apt-get install mysql...
在Ubuntu下使用Python连接数据库,通常需要安装相应的数据库驱动和库。以下是一些常见数据库的连接操作:
- MySQL
首先,安装MySQL数据库和Python的MySQL驱动:
sudo apt-get install mysql-server
pip install mysql-connector-python
然后,使用Python连接MySQL数据库:
import mysql.connector
# 创建连接
cnx = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 创建游标
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
- PostgreSQL
首先,安装PostgreSQL数据库和Python的PostgreSQL驱动:
sudo apt-get install postgresql postgresql-contrib
pip install psycopg2
然后,使用Python连接PostgreSQL数据库:
import psycopg2
# 创建连接
cnx = psycopg2.connect(
dbname="your_database",
user="your_username",
password="your_password",
host="localhost"
)
# 创建游标
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
- SQLite
SQLite是一个轻量级的数据库,无需安装额外的驱动。使用Python内置的sqlite3库连接SQLite数据库:
import sqlite3
# 创建连接
cnx = sqlite3.connect("your_database.db")
# 创建游标
cursor = cnx.cursor()
# 执行SQL查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取查询结果
for row in cursor.fetchall():
print(row)
# 关闭游标和连接
cursor.close()
cnx.close()
根据需要选择合适的数据库,并按照相应的步骤进行操作。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Ubuntu下Python数据库连接如何操作
本文地址: https://pptw.com/jishu/777742.html
