import pymysql
#主机名 用户 密码 库
db = pymysql.connect("localhost", "root", "fs.com", "test")
#创建对象
cursor = db.cursor()
#给出执行sql语句
sql = "select version()"
#执行
cursor.execute(sql)
#过去返回信息
data = cursor.fetchall()
print(data)
#断开
cursor.close()
db.close()
创建数据库表:
import pymysql
db = pymysql.connect("localhost", "root", "fs.com", "test")
cursor = db.cursor()
cursor.execute(drop table if exists bandcard)
建立表
sql = 'create tabele bandcard (
id int auto_increment primary key,
money int not null
)''
cursor.close()
db.close()
插入数据:
如果插入数据错误,回滚之前状态
try :
cursor.execute(sql)
db.commit()
except:
db.rollback
查询操作:
fetchone()
获取下一个查询结果集,结果集是一个对象
fetchall()
接受全部的返回的行
rowcount()
是一个只读属性,返回 execute() 方法影响的行数
import pymysql
db = pymysql.connect("localhost", "root", "fs.com", "test")
cursor = db.cursor()
sql = 'select * from bandcard where money > 400'
try :
cursor.execute(sql)
reslist = cursor.fetchall()
for row in reslist:
print ("%d-%d" % (row[0], row[1]))
except:
db.rollback
打包:
import pymysql
class userSql():
def __init__(self, host, user, passwd, dbName):
self.host = host
self.user = user
self.passwd = passwd
self.db = dbName
def 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 = None
try :
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchone()
except:
print("查询失败")
return res
def get_all(self, sql):
res = ()
try :
self.connet()
self.cursor.execute(sql)
res = self.cursor.fetchall()
except:
print("查询失败")
return res
def insert(self, sql):
return self.__edit(sql)
def delete(self, sql):
return self.__edit(sql)
def update(self, sql):
return self.__edit(sql)
def __edit(self, sql):
count = 0
try :
self.count()
count = self.cursor.execute(sql)
self.db.rollback
self.close()
except:
print("事务提交失败")
self.db.rollback
使用
from userSql import userSql
s = userSql("localhost", "root", "fs.com", "test")
res = s.get_all("select * from test")
for row in res:
print ("%d-%d" % (row[0], row[1]))