在Python中连接数据库通常需要使用特定的数据库驱动模块,以下是一些常用的数据库连接方式及示例代码:
MySQL连接
使用`pymysql`模块
1. 安装`pymysql`模块:
pip install pymysql
2. 连接数据库的示例代码:
import pymysql连接数据库conn = pymysql.connect(host='localhost',user='root',password='redhat',db='helloTest',charset='utf8',autocommit=True 自动提交事务)创建游标对象cur = conn.cursor()执行SQL语句cur.execute("CREATE TABLE IF NOT EXISTS hello (id INT, name VARCHAR(30))")插入数据cur.execute("INSERT INTO hello (id, name) VALUES (1, 'Alice')")提交事务conn.commit()关闭游标和连接cur.close()conn.close()
使用`mysql-connector-python`模块
1. 安装`mysql-connector-python`模块:
pip install mysql-connector-python
2. 连接数据库的示例代码:
import mysql.connector连接数据库conn = mysql.connector.connect(host='localhost',user='root',password='redhat',database='helloTest',charset='utf8mb4')创建游标对象cur = conn.cursor()执行SQL语句cur.execute("CREATE TABLE IF NOT EXISTS hello (id INT, name VARCHAR(30))")插入数据cur.execute("INSERT INTO hello (id, name) VALUES (1, 'Alice')")提交事务conn.commit()关闭游标和连接cur.close()conn.close()

PostgreSQL连接
使用`psycopg2`模块
1. 安装`psycopg2`模块:
pip install psycopg2
2. 连接数据库的示例代码:
import psycopg2连接数据库conn = psycopg2.connect(host='localhost',user='root',password='redhat',dbname='helloTest',charset='utf8')创建游标对象cur = conn.cursor()执行SQL语句cur.execute("CREATE TABLE IF NOT EXISTS hello (id SERIAL, name VARCHAR(30))")插入数据cur.execute("INSERT INTO hello (name) VALUES ('Alice')")提交事务conn.commit()关闭游标和连接cur.close()conn.close()
SQLite连接
使用`sqlite3`模块
1. 连接数据库的示例代码:
import sqlite3连接数据库conn = sqlite3.connect('database.db')创建游标对象cur = conn.cursor()执行SQL语句cur.execute("CREATE TABLE IF NOT EXISTS hello (id INTEGER PRIMARY KEY, name VARCHAR(30))")插入数据cur.execute("INSERT INTO hello (name) VALUES ('Alice')")提交事务conn.commit()关闭游标和连接cur.close()conn.close()
请根据你的数据库类型选择合适的模块和连接方式,并确保在使用前已经正确安装了相应的模块。
