01
import pymysql#连接数据库db= pymysql.connect("192.168.1.179","root","liuwang","liu")#创建一个cursor对象
cursor= db.cursor()
sql = "select version()"cursor.execute(sql)data = cursor.fetchone()
print(data)#断开
cursor.close()
db.close()
02 创建数据库
import pymysqldb= pymysql.connect("192.168.1.179","root","liuwang","liu")
cursor= db.cursor()#检查表是否存在,如果存在则删除
cursor.execute("drop table if exists bandcard")#
sql = "create table bandcard(id int auto_increment primary key,money int not null)"
cursor.execute(sql)cursor.close()
db.close()
03 数据库插入数据
import pymysqldb= pymysql.connect("192.168.1.179","root","liuwang","liu")
cursor= db.cursor()sql = "insert into bandcard values(0,100)"
try:cursor.execute(sql)db.commit()
except:#如果提交失败回滚到上一次数据db.rollback()cursor.close()
db.close()
04数据库更新操作
import pymysqldb= pymysql.connect("192.168.1.179","root","liuwang","liu")
cursor= db.cursor()sql = "insert into bandcard set money=1100 where id=1"
try:cursor.execute(sql)db.commit()
except:#如果提交失败回滚到上一次数据db.rollback()cursor.close()
db.close()
05数据库删除操作
import pymysqldb= pymysql.connect("192.168.1.179","root","liuwang","liu")
cursor= db.cursor()sql = "delete from bandcard where money =100"
try:cursor.execute(sql)db.commit()
except:#如果提交失败回滚到上一次数据db.rollback()cursor.close()
db.close()
06数据库查询
'''fetchone()
功能:获取下一个查询结果集,结果集是一个对象fetchall()
功能:接受全部返回的行rowcount : 是一个只读属性,返回execute()方法影响行数
'''
import pymysqldb= pymysql.connect("192.168.1.179","root","liuwang","liu")
cursor= db.cursor()sql = "select * from bandcard where money>300"
try:cursor.execute(sql)reslist = cursor.fetchall()for row in reslist:print("%d-%d"%(row[0],row[1]))
except:#如果提交失败回滚到上一次数据db.rollback()cursor.close()
db.close()
07 整理封装
import pymysqlclass LiuSql():def __init__(self,host,user,passwd,dbName):self.host = hostself.user = userself.passwd = passwdself.dbName = dbNamedef connet(self):self.db = pymysql.connect(self.host,self.user,self.passwd,self.dbName)self.cursor = self.db.cursor()def close(self):self.cursor.close()self.db.close()def get_one(self,sql):res = Nonetry:self.connet()self.cursor.execute(sql)res = self.cursor.fetchone()self.close()except:print("查询失败")return resdef get_all(self,sql):res = ()try:self.connet()self.cursor.execute(sql)res = self.cursor.fetchall()self.close()except:print("查询失败")return resdef insert(self,sql):return self.__edit(sql)def updata(self,sql):return self.__edit(sql)def delete(self,sql):return self.__edit(sql)def __edit(self,sql):count =0try:self.connet()count= self.cursor.execute(sql)self.db.commit()self.close()except:print("提交失败")self.db.rollback()return count