Python全栈开发之---mysql数据库

时间:2023-03-08 19:32:55
Python全栈开发之---mysql数据库

1、数据库的安装和连接

 #数据库安装
pip install PyMySQL #数据库操作
import pymysql db = pymysql.connect("数据库ip","用户","密码","数据库" ) # 打开数据库连接
cursor.execute("SELECT VERSION()") # 使用 execute() 方法执行 SQL 查询
data = cursor.fetchone() # 使用 fetchone() 方法获取单条数据
print ("Database version : %s " % data)
db.close() # 关闭数据库连接 import pymysql conn = pymysql.connect(
host='localhost', user='root', password="root",
database='db', port=3306, charset='utf-8',
) cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

2、创建表操作

 import pymysql

 # 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法获取操作游标
cursor = db.cursor() # SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
cursor.execute(sql) # 执行sql语句
db.commit() # 提交到数据库执行
except:
db.rollback() # 如果发生错误则回滚 # 关闭数据库连接
db.close() import pymysql # 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法获取操作游标
cursor = db.cursor() # SQL 插入语句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES (%s, %s, %s, %s, %s )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try: cursor.execute(sql) # 执行sql语句
db.commit() # 执行sql语句
except:
db.rollback() # 发生错误时回滚 # 关闭数据库连接
db.close() 另一种形式

3、查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

  • fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  • fetchall(): 接收全部的返回结果行.
  • rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
 import pymysql

 # 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法获取操作游标
cursor = db.cursor() # SQL 查询语句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %s" % (1000)
try: cursor.execute(sql)# 执行SQL语句
results = cursor.fetchall()# 获取所有记录列表
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印结果
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income ))
except:
print ("Error: unable to fetch data") # 关闭数据库连接
db.close()

4、更新操作

 import pymysql

 # 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法获取操作游标
cursor = db.cursor() # SQL 更新语句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')
try:
cursor.execute(sql) # 执行SQL语句
db.commit() # 提交到数据库执行
except
db.rollback() # 发生错误时回滚 # 关闭数据库连接
db.close()

5、删除操作

 import pymysql

 # 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用cursor()方法获取操作游标
cursor = db.cursor() # SQL 删除语句
sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)
try
cursor.execute(sql) # 执行SQL语句
db.commit() # 提交修改
except
db.rollback() # 发生错误时回滚# 关闭连接
db.close()