pycharm和MySQL
安装pymysql:pip install pymysql
建立连接:conn = pymysql.connect(host=' ', port=3306, user=' ', password=' ', db=' ', charset='utf8')
注意编码是utf8
cursor方法返回游标对象
with conn.sursor() as cursor:
cursor.execute(str)
execute代表执行,str是SQL语句
默认情况下事务不自动提交,所以成功需要提交commit,失败就回滚
try:
with conn.cursor() as cursor:
result = cursor.execute(str)
if resulr == 1:
print('添加成功‘)
conn.commit()
except pymysql.MySQLError as error:
print(error)
connect.rollback()
finally:
conn.close()
运行成功返回1
---------------------------------
使用pycharm实现delete操作:
name = input('要删除的学生名字是: ')
with conn.sursor() as cursor:
cursor.execute('delete from tb_student where student_name = %s', (name, )
注意后面可以是元组,也可以是字典,列表
-------------------------------------
使用pycharm实现update操作:
name = input('要更新的学生名字是: ')
address = input('要更新的学生地址是: ')
with conn.sursor() as cursor:
cursor.execute('update tb_student set student_addr = %s where student_name = %s', (addr, name, ))
元组里有俩个参数,与传入参数顺序要对应
--------------------------------------------
使用pycharm实现select操作:
with conn.sursor() as cursor:
cursor.execute('select student_id, student_name, student_addr from tb_student')
# 注意不要用*代替要查询内容,用*在底层会查询两次,影响效率,要把需要查询的内容都打出来
cursor.fetchall ()#查询所有的结果,结果是一个元组,所以可以用for循环取出结果
cursor.fetchone() # 只拿到第一条结果
cursor.fetchmany(2) # 拿到两条结果
--------------------------------------------------
游标对象类型可以选择字典,更方便处理数据:
conn = pymysql.connect(host=' ', port=3306, user=' ', password=' ', db=' ', charset='utf8, cursorclass=pymysql.cursors.DictCursor')
cursor.fetchone()
这时候拿到的结果就是一个字典,for循环后用键值对获取值