码迷,mamicode.com
首页 > 数据库 > 详细

python3连接mysql--增删改查

时间:2018-05-13 13:46:47      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:named   增删改   sele   执行sql   mysql   pre   hal   com   print   

ps:MYSQLdb只适用于python2.x

python3不支持MYSQLdb,取而代之的是pymysql

运行会报:ImportError:No module named ‘MYSQLdb‘

 

 

import pymysql as pmq

#connect(ip.user,password,dbname)
con = pmq.connect(localhost,root,123456,python_test)
#操作游标
cur = con.cursor()

#建表
cur.execute("CREATE TABLE IF NOT EXISTS  Writers(Id INT PRIMARY KEY AUTO_INCREMENT,Name VARCHAR(25))")

#插入数据一
cur.execute("INSERT INTO Writers(Name) VALUES(‘Jack London‘)")
cur.execute("INSERT INTO Writers(Name) VALUES(‘Honore de Balzac‘)")
cur.execute("INSERT INTO writers VALUES(1,‘Jack London‘)")
cur.execute("INSERT INTO writers VALUES(2,‘Honore de Balzac‘)")

#提交到数据库 -------ps:不写这一行无法插入
con.commit()

#插入数据二
sql="INSERT INTO Writers(Name) VALUES(‘Jack London2‘)"
try:
#执行sql语句
cur.execute(sql)
#提交到数据库执行
con.commit()
except:
#如果发生错误则回滚
con.rollback()

 

1 #查询
2 cur.execute(select * from writers)
3 
4 results = cur.fetchall()
5 
6 for row in results:
7     Id = row[0]
8     Name = row[1]
9     print("id=%s,name=%s" % (Id,Name))

 

 1 #更新
 2 Id= 1
 3 sql ="update writers set Name=‘updateJackto‘ where Id = {0}".format(Id)
 4 try:
 5     cur.execute(sql)
 6     con.commit()
 7 except:
 8     con.rollback()
 9     
10 #删除
11 Id=7
12 sql = "delete from writers where Id = {0}".format(Id)
13 try:
14     cur.execute(sql)
15     con.commit()
16 except:
17     con.rollback()

 

python3连接mysql--增删改查

标签:named   增删改   sele   执行sql   mysql   pre   hal   com   print   

原文地址:https://www.cnblogs.com/chenlove/p/9031460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!