'''
phpStudy2017
db:user
table:apple_id
fields:email,phone,comment
unique key:email
'''
import pymysql
'''使用PyMySQL模块固定不变的执行顺序
1. 建立连接
2. 拿到游标
3. 执行SQL语句
4. 事务处理(提交修改)
5. 关闭(游标、连接)
游标(cursor)是系统为用户开设的一个数据缓冲区,存放SQL语句的执行结果。
每个游标区都有一个名字。
用户可以用SQL语句逐一从游标中获取记录,并赋给主变量,交由主语言进一步处理。
'''
class MySql():
def __init__(self, password, db_name, table):
self.table = table
self.con = pymysql.connect(host="localhost", user="root", password=password, database=db_name, port=3306)
self.cur = self.con.cursor()
def fetchall(self):
self.cur.execute("SELECT * FROM {}".format(self.table))
data = self.cur.fetchall()
return data
def fetchone(self):
self.cur.execute("SELECT * FROM {} limit 1".format(self.table))
data = self.cur.fetchall()
return data
def insert(self, email, phone, comment):
try:
add_sql = " insert into {}(email,phone,comment) values (%s,%s,%s) ".format(self.table)
self.cur.execute(add_sql, (email, phone, comment))
self.con.commit()
print('执行成功!')
except Exception as e:
print(u'错误提示...', e)
self.con.rollback()
finally:
...
def delete(self, email):
try:
sql = "delete from {} where email='{}'".format(self.table, email)
self.cur.execute(sql)
self.con.commit()
except Exception as e:
print(u'错误提示...', e)
if __name__ == '__main__':
db = MySql('root', 'user', 'apple_id')
db.insert("111@qq.com", "16620122910", "xiuxian")
r = db.fetchall()
print(r)