常见的数据库操作的方法封装:
import pymysql
class DbFunc():
def __init__(self,host,port,user,pwd,name,charset):
self.host = host
self.port = port
self.user = user
self.pwd = pwd
self.name = name
self.charset = charset
self.sql = ""
self.conn = None
def connectsql(self):
#链接数据库
try:
self.conn = pymysql.connect(self.host, user=self.user, passwd=self.pwd, db=self.name)
cursor = self.conn.cursor()
print("数据库链接成功")
return cursor
except pymysql.Error as e:
print(e)
def get_one(self,sql):
#获取符合sql语句中的第一条
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchone()
except pymysql.Error as e:
print(e)
def get_all(self,sql):
#获取符合sql语句的所有数据
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchall()
except pymysql.Error as e:
print(e)
def get_many(self,sql,n):
#获取符合sql语句中的部分
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchmany(n)
except pymysql.Error as e:
print(e)
def update(self,sql):
#更新数据库操作
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.Error as e :
print(e)
def alert_add(self,sql):
#增加一列
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.Error as e:
print(e)
def alert_modify(self,sql):
#更改一列的数据类型
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.Error as e:
print(e)
if __name__ == '__main__':
host = "127.0.0.1"
port = "3306"
user = "root"
pwd = "Dy******5"
name = "django_demo"
charset = "utf-8"
sql1 = "select * from booktest_heroinfo;"
sql = "update booktest_heroinfo set actor_content='打大美女' where id=2;"
sql2 = "alter table booktest_heroinfo add column actor_TV varchar(20);"
sql3 = "alter table date_test modify sid varchar(30);"
cursor = DbFunc(host,port,user,pwd,name,charset)
# print(cursor.get_one(sql))
# print(cursor.get_all(sql))
# print(cursor.get_many(sql,2))
# print(cursor.update(sql))
# print(cursor.get_all(sql1))
# print(cursor.alert_add(sql2))
print(cursor.alert_modify(sql3))