python操作mysql数据库

Posted bkwxx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作mysql数据库相关的知识,希望对你有一定的参考价值。

先简单写一个操作mysql数据库类,后面再改进

# -*- coding:utf-8 -*-
import pymysql

class SunckSql():
def __init__(self,host,user,password,database,port):
self.host=host
self.user=user
self.passwd=password
self.dbName=database
self.port=port

def connect(self):
self.db = pymysql.connect(self.host,self.user,self.passwd,self.dbName,self.port)
self.cursor=self.db.cursor()

def close(self):
self.cursor.close()
self.db.close()

def get_one(self,sql):
res=None
try:
self.connect()
self.cursor.execute(sql)
res=self.cursor.fetchone()
except Exception as e:
print(e)
print("查询失败")
finally:
self.close()
return res

def get_all(self,sql):
res=()
try:
self.connect()
self.cursor.execute(sql)
res=self.cursor.fetchall()
except Exception as e:
print(e)
print("查询失败")
finally:
self.close()
return res

def insert(self,sql):
count=0
try:
self.connect()
count=self.cursor.execute(sql)
print("插入数据成功")
self.db.commit()
except Exception as e:
print(e)
print("插入数据失败")
self.db.rollback()
finally:
self.close()
return count

def update(self,sql):
count = 0
try:
self.connect()
count = self.cursor.execute(sql)
print("数据更新成功")
self.db.commit()
except Exception as e:
print(e)
print("数据更新失败")
self.db.rollback()
finally:
self.close()
return count

def delete(self,sql):
count = 0
try:
self.connect()
count = self.cursor.execute(sql)
print("删除数据成功")
self.db.commit()
except Exception as e:
print(e)
print("数据删除失败")
self.db.rollback()
finally:
self.close()
return count

if __name__ == ‘__main__‘:
s = SunckSql(host="xxx", user=‘xxx‘, password=‘xxx‘, database=‘xx‘, port=xx)
# res = s.get_all("select * from ce")
# for row in res:
# print("%d----%s" % (row[0], row[1]))
# s.delete("delete from ceshi where id=10")
# s.insert("insert into bk values (3,‘bk‘)")
# t=s.get_one("select * from bk where id=15")
# print(t)
# s.update("update bk set name=‘hg1‘ where id=3")
s.delete("delete from bk where id=3")




































































































以上是关于python操作mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章

部分代码片段

在 Python代码中操作mysql数据

通过Python代码操作MySQL:

python 用于数据探索的Python代码片段(例如,在数据科学项目中)

如何在片段中填充列表视图?

用python操作mysql数据库(之代码归类)