在使用pymysql 之前需要先下载 PyMySQL第三方库
pip install PyMySQL
一、简单连接数据库的流程
import pymysql # 导入模块
conn = pymysql.connect(host='IP地址', port=端口号, user='用户名', password='密码', charset="utf8")
print("连接成功")
coursor=conn.cursor() # 创建游标
pymysql.cursors.DictCursor # 得到一个可以执行SQL语句并且将结果作为字典返回的游标
coursor.execute("use ai_stadium_qa") # 执行语句
print(coursor.fetchall()) # 显示查询的内容
coursor.execute("insert/update/alter/delete/drop…………")
conn.commit() # 对表数据 增删改 的操作时需要进行提交
二、操作数据库:
1、增加表
coursor.execute('create table student (name char(10),age char(10),sex char(10),fen char(10))')
conn.commit()
coursor.execute('show tables')
print("数据库表名:{}".format(coursor.fetchall()))
2、删除表
coursor.execute('drop table student') #delete from student where age >%s %(xx)删除表的数据
conn.commit()
coursor.execute('show tables')
print("数据库表名:{}".format(coursor.fetchall()))
3、修改表
coursor.execute('alter table test add (sex char(10),grands char(10))') #添加多个字段
conn.commit()
coursor.execute('desc test') #查看表结构有没有增加字段
print("数据库表名:{}".format(coursor.fetchall()))
在执行SQL中,有事数据可以不是固定的,或者不能直接写在SQL中,有两种拼接方式:
3.1、第一种:占位方式,但是这种方式不太好
x=("蟠桃","100000","仙","9999")
coursor.execute('insert into test (name,age,sex,grands)values ("%s","%s","%s","%s")' % x ) # 插入表的数据
3.2、第二种方式,推荐使用
sql = "insert into test (name,age,sex,grands)values (%s, %s, %s, %s)"
value = ("蟠桃","100000","仙","9999")
coursor.execute(sql, value) # 可以防止SQL注入
conn.commit()
coursor.execute('select * from test')
print("数据库表名:{}".format(coursor.fetchall()))
4、查询表内容
coursor.execute('select * from test where age>%s'%(1000)) #查询条件
print("提交后:{}".format(coursor.fetchall()))
row=coursor.fetchall() #获取所有记录列表
for i in row:
name=i[0]
age=i[1]
sex=i[2]
grands=i[3]
print(name,age,sex,grands)
coursor.close() #关闭游标
conn.close() #关闭数据库 --------为了防止报错,可以使用try--except--else来关闭数据库,以免消耗内存