以Mysql为例:

 

要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection;

连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

 

 

 

1。安装驱动

$ pip install mysql-connector-python --allow-external mysql-connector-python

或者尝试:

$ pip install mysql-connector

安装过程如下:

2.使用代码连接

  

# 导入驱动
import mysql.connector

# 连接信息
conn = mysql.connector.connect(user="root", password="root", database="sakila")
# 获取游标
cursor = conn.cursor()
# 运行查询
cursor.execute("SELECT * FROM actor WHERE first_name = %s", ("NICK",))
# 获取结果
values = cursor.fetchall()
print(values)
# 关闭连接
cursor.close()
conn.close()

  注意占位符的使用

 

转载于:https://www.cnblogs.com/jiangbei/p/10997526.html

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐