python 数据库

怎么用python连接数据库

小亿
111
2023-09-28 03:58:40
栏目: 编程语言
亿速云数据库,弹性扩容,低至0.3元/天! 查看>>

要用Python连接数据库,你需要安装相应的数据库驱动程序。下面是一些常用的数据库连接库和连接步骤示例:

  1. 使用MySQL数据库:
import mysql.connector
# 建立连接
cnx = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="dbname"
)
# 执行SQL查询
cursor = cnx.cursor()
cursor.execute("SELECT * FROM table_name")
# 获取结果
result = cursor.fetchall()
# 关闭连接
cursor.close()
cnx.close()
  1. 使用SQLite数据库:
import sqlite3
# 建立连接
conn = sqlite3.connect('database.db')
# 执行SQL查询
cursor = conn.cursor()
cursor.execute('SELECT * FROM table_name')
# 获取结果
result = cursor.fetchall()
# 关闭连接
cursor.close()
conn.close()
  1. 使用PostgreSQL数据库:
import psycopg2
# 建立连接
conn = psycopg2.connect(
host="localhost",
database="dbname",
user="username",
password="password"
)
# 执行SQL查询
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
# 获取结果
result = cursor.fetchall()
# 关闭连接
cursor.close()
conn.close()

以上是连接数据库的基本示例,你可以根据你使用的数据库类型和具体需求进行适当的修改。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

相关推荐:linux python如何连接数据库

0
看了该问题的人还看了