怎么用python连接数据库

   2025-02-20 7150
核心提示:要用Python连接数据库,你需要安装相应的数据库驱动程序。下面是一些常用的数据库连接库和连接步骤示例:使用MySQL数据库:安装M

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

使用MySQL数据库:

安装MySQL驱动程序:pip install mysql-connector-python

连接数据库:

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()
使用SQLite数据库:

安装SQLite驱动程序:无需安装,Python内置支持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()
使用PostgreSQL数据库:

安装PostgreSQL驱动程序:pip install psycopg2

连接数据库:

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()

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言