python3连接mysql--增删改查

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()

 

posted @ 2018-05-13 11:00  Python研究者  阅读(1720)  评论(0编辑  收藏  举报