The sixth question of the interview:
Part 1 - Test Site:
Operate the MySQL database:
- Create MySQL data table;
- insert records into the table;
- Other database operations.
Part 2 - Interview Questions:
1. Interview question 1: How to create a MySQL data table?
2. Interview question 2: How to insert data into MySQL table?
3. Interview question 3: How to query data in MySQL?
Part 3 - Analysis:
One of the interview questions to create a MySQL data table:
# coding=utf-8
# _author__ = 孤寒者
from pymysql import *
def connectDB():
'''
连接本地MySQL数据库,指定连接的库为test库。
:return:
'''
db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
return db
db = connectDB()
print(type(db))
def createTable(db):
c = db.cursor()
try:
c.execute('''create table persons
(id int primary key not null,
name text not null,
age int not null,
address char(100),
salary real);''')
db.commit()
db.commit()
return True
except:
db.rollback()
return False
if createTable(db):
print('create table success')
else:
print('create table failed')
Use the navicat tool to view:
Interview question 2 inserting data into MySQL table:
# coding=utf-8
# _author__ = 孤寒者
from pymysql import *
def connectDB():
'''
连接本地MySQL数据库,指定连接的库为test库。
:return:
'''
db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
return db
db = connectDB()
print(type(db))
def insertRecords(db):
cursor = db.cursor()
try:
cursor.execute("delete from persons")
cursor.execute('''
insert into persons(id,name,age,address,salary)
values(1, 'GuHanZhe', 18, 'China', 9999)
''')
cursor.execute('''
insert into persons(id,name,age,address,salary)
values(2, 'XiaoZhang', 55, 'China', 9)
''')
db.commit()
return True
except Exception as e:
print(e)
db.rollback()
return False
if insertRecords(db):
print("成功插入记录")
else:
print("插入记录失败")
Use the navicat tool to view:
Interview question 3: Query data in MySQL:
# coding=utf-8
# _author__ = 孤寒者
from pymysql import *
def connectDB():
'''
连接本地MySQL数据库,指定连接的库为test库。
:return:
'''
db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
return db
db = connectDB()
def selectRecords(db):
cursor = db.cursor()
sql = 'select name,age,salary from persons order by age desc'
cursor.execute(sql)
results = cursor.fetchall()
print(results)
print(type(results)) # 打印发现是元组类型
selectRecords(db)
db.close()
- We found that the output type of the query data is a tuple type. What should we do if we want to pair the field name with the queried data?
- Here we need to use two very commonly used functions dict() and zip(), as follows:
# coding=utf-8
# _author__ = 孤寒者
import json
from pymysql import *
def connectDB():
'''
连接本地MySQL数据库,指定连接的库为test库。
:return:
'''
db = connect(host='localhost', user='root', password='123456', port=3306, db='test')
return db
db = connectDB()
def selectRecords(db):
cursor = db.cursor()
sql = 'select name,age,salary from persons order by age desc'
cursor.execute(sql)
results = cursor.fetchall()
print(results)
print(type(results)) # 打印发现是元组类型
# 将字段名和查询结果整合在一起
fields = ['name', 'age', 'salary']
records = []
for row in results:
records.append(dict(zip(fields, row)))
return json.dumps(records) # 输出类型为JSON字符串
endresults = selectRecords(db)
print(endresults)
db.close()
Part 4 - Conclusion:
- Note: We use the API in the pymysql module to operate the MySQL database, this module needs to be installed separately~