import pymysql

1、pip install pymysql

 

 

 2、连接数据库,并创建表,插入数据

import pymysql
# 1. 连接数据库,
db = pymysql.connect("localhost", "root", "1234abcd", "test")
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = db.cursor()
# 3. 对于数据库进行增删改查
# 1). ************************创建数据表**********************************
try:
create_sqli = "create table hello (id int, name varchar(50));"
# 执行创建表
cur.execute(create_sqli)
# try后面的执行失败,给出提示
except Exception as e:
print("创建数据表失败:", e)
# try后面执行成功,给出提示
else:
print("创建数据表成功;")
## 2). *********************插入数据****************************
try:
insert_sqli = "insert into hello values(2, 'fensi');"
cur.execute(insert_sqli)
except Exception as e:
print("插入数据失败:", e)
else:
# 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
db.commit()
print("插入数据成功;")
# 4. 关闭游标
cur.close()
# 5. 关闭连接
db.close()

运行结果:

 

 

3、插入多条数据

import pymysql
# 1. 连接数据库,
db = pymysql.connect("localhost", "root", "1234abcd", "test")
# ****python, 必须有一个游标对象, 用来给数据库发送sql语句, 并执行的.
# 2. 创建游标对象,
cur = db.cursor()

# 1). ************************创建数据表**********************************
try:
create_sqli = "create table hello (id int, name varchar(50));"
# 执行创建表
cur.execute(create_sqli)
# try后面的执行失败,给出提示
except Exception as e:
print("创建数据表失败:", e)
# try后面执行成功,给出提示
else:
print("创建数据表成功;")

# 插入多条数据
try:
info = [(i, "westos%s" %(i)) for i in range(100)]
insert_sqli = "insert into hello values(%s, %s);"
cur.executemany(insert_sqli, info )
except Exception as e:
print("插入多条数据失败:", e)
else:
# 如果是插入数据, 一定要提交数据, 不然数据库中找不到要插入的数据;
db.commit()
print("插入多条数据成功;")

# **************************数据库查询*****************************
sqli = "select * from hello;"
result = cur.execute(sqli) # 默认不返回查询结果集, 返回数据记录数。
print(result)
print(cur.fetchone()) # 1). 获取下一个查询结果集;
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchmany(4)) # 2). 获取制定个数个查询结果集;
info = cur.fetchall() # 3). 获取所有的查询结果
print(info)
print(len(info))
print(cur.rowcount) # 4). 返回执行sql语句影响的行数
# 5). 移动游标指针
print(cur.fetchmany(3))
print("正在移动指针到最开始......")
cur.scroll(0, 'absolute')
print(cur.fetchmany(3))
print("正在移动指针到倒数第2个......")
print(cur.fetchall()) # 移动到最后
cur.scroll(-2, mode='relative')
print(cur.fetchall())
# 4. 关闭游标
cur.close()
# 5. 关闭连接
db.close()
posted @ 2020-08-20 16:27  蜕变1  阅读(5765)  评论(0编辑  收藏  举报