最近在学习pymysql模块所以话不多说,直接进入正题:
第一步导入pymysql
import pymysql
第二步打开数据库,这里要注意指定参数名,并填写相应的值,password就是这个数据库进入的密码,database是创建的数据库名称test
db = pymysql.connect(host=“localhost”, user=“root”, password=“password”,
database=“test”)
第三步,使用cursor()方法准备一个cursor对象
cursor = db.cursor()
游标(cursor)是一个存储在DBMS服务器上的数据库查询,它不是一条SELECT语句,而是被该语句检索出来的 结果集第四步,使用execute()方法执行SQL查询。
cursor.execute("SELECT VERSION()")
第五步,使用fetchone()方法获取单行赋给对象data并打印。
data = cursor.fetchone()
print ("Database version : %s " % data)
可以看出查询的是mysql版本,这里的%s %data我猜是两者匹配,如果有大佬知道还望在评论区指点。
第六步,关闭
db.close()
运行结果如下:
Database version : 8.0.22
[Finished in 0.3s]
完整代码如下:
import pymysql
# Open database connection
db = pymysql.connect(host="localhost", user="root", password="password",
database="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
从使用cursor()方法准备一个cursor对象开始使用代码,如果employee存在则丢掉表,没有则创建:
cursor.execute(“DROP TABLE IF EXISTS employee”)
接着使用mysql语句编写建表代码:
sql = “”“CREATE TABLE
employee
(
id
int(10) NOT NULL AUTO_INCREMENT,
first_name
char(20) NOT NULL,
last_name
char(20) DEFAULT NULL,
age
int(11) DEFAULT NULL,
sex
char(1) DEFAULT NULL,
income
float DEFAULT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;”""
cursor.execute(sql)
print(“Created table Successfull.”)
完成后关闭连接,发现test数据库中有了employee表
完整代码如下:
import pymysql
# Open database connection
db = pymysql.connect(host="localhost", user="root", password="password",
database="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS employee")
# Create table as per requirement
sql = """CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`first_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
cursor.execute(sql)
print("Created table Successfull.")
# disconnect from server
db.close()
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('nanshen', 'Zhang', 20, 'M', 5000)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
重复以上操作给表中插入张妹妹的数据,成功操作如图所示: ![sql插入成功操作](https://img-blog.csdnimg.cn/20210220203852938.png)
完整代码如下:
import pymysql
# Open database connection
db = pymysql.connect(host="localhost", user="root", password="password",
database="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('nanshen', 'Zhang', 20, 'M', 5000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
print (sql)
print('Yes, Insert Successfull.')
# disconnect from server
db.close()
# Prepare SQL query to select a record from the table.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > %d" % (1000)
#print (sql)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
#print (row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
# Now print fetched result
print ("name = %s %s,age = %s,sex = %s,income = %s" % \
(fname, lname, age, sex, income ))
except:
import traceback
traceback.print_exc()
print ("Error: unable to fetch data")
读取成功!这里的print中的反斜杠\不知道啥意思,我去了也没影响,可能是换行?蹲大佬解答…
name = nanshen Zhang,age = 20,sex = M,income = 5000.0
name = meimei Zhang,age = 16,sex = W,income = 10000.0
[Finished in 0.3s]
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 \
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
更新成功,可以看到张男神从20岁变成了21岁,而张妹妹还是16岁
总的来说,可以看出以上的操作相当固定,只需要掌握mysql语句就能很好的理解以上代码。
参考链接: