数据库连接与增删改查操作
'''数据库连接'''
from pymysql import *
conn=connect(host='localhost',port=3306,user='root',password='123456',db='testdb')
cursor=conn.cursor()
cursor.execute("SELECT VERSION()")
data=cursor.fetchone()
print("Database version : %s " % data)
print(conn)
conn.close()
'''插入数据'''
conn=connect(host="localhost",port=3306,user='root',password='123456',db='testdb')
cursor=conn.cursor()
sql="""INSERT INTO USER(ID,NAME) VALUES (1,'zhangsan')"""
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
conn.close()
'''查询数据'''
db=connect(host="localhost",port=3306,user='root',password='123456',db='testdb')
cursor=db.cursor()
sql="select * from user "
try:
cursor.execute(sql)
results=cursor.fetchall()
for row in results:
id=row[0]
name=row[1]
print("id=%s,name=%s"%(id,name))
except:
print("无法获取数据")
db.close()
'''更新数据'''
db=connect(host="localhost",port=3306,user='root',password='123456',db='testdb')
cursor=db.cursor()
sql="update user set name='Alice' where id=5 "
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
'''删除数据'''
db=connect(host="localhost",port=3306,user='root',password='123456',db='testdb')
cursor=db.cursor()
sql="delete from user where id=7"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()