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()
#查询
cur.execute('select * from writers')
results = cur.fetchall()
for row in results:
Id = row[0]
Name = row[1]
print("id=%s,name=%s" % (Id,Name))
#更新
Id= 1
sql ="update writers set Name='updateJackto' where Id = {0}".format(Id)
try:
cur.execute(sql)
con.commit()
except:
con.rollback()
#删除
Id=7
sql = "delete from writers where Id = {0}".format(Id)
try:
cur.execute(sql)
con.commit()
except:
con.rollback()