1.导入pymysql库
import pymysql
2.实例属性
def __init__(self,host,port,database,name,passwd,sql):
self.host = host
self.port = port
self.database = database
self.name = name
self.passwd = passwd
self.sql = sql
3.建立连接
def conn(self):
coon = pymysql.connect( host=self.host,
port=self.port,
database=self.database,
user=self.name,
passwd=self.passwd)
4.建立游标
cur = coon.cursor()
5.判断SQL语句
try:
if str(self.sql).startswith('s'):
cur.execute(self.sql)
all_score = cur.fetchall()
for i in all_score:
print(i)
else:
cur.execute(self.sql)
coon.commit()
6.关闭游标,关闭连接
finally:
cur.close()
coon.close()
7.调用
if __name__ == '__main__':
test1 = Mysql_Connect('127.0.0.1', 3306, 'mydb_test',
'root', '229544','select * from student_score')
test1.conn()
8.完整代码
import pymysql
class Mysql_Connect():
def __init__(self,host,port,database,name,passwd,sql):
self.host = host
self.port = port
self.database = database
self.name = name
self.passwd = passwd
self.sql = sql
def conn(self):
coon = pymysql.connect( host=self.host,
port=self.port,
database=self.database,
user=self.name,
passwd=self.passwd)
cur = coon.cursor()
try:
if str(self.sql).startswith('s'):
cur.execute(self.sql)
all_score = cur.fetchall()
for i in all_score:
print(i)
else:
cur.execute(self.sql)
coon.commit()
except:
print('SQL有误')
finally:
cur.close()
coon.close()
if __name__ == '__main__':
test1 = Mysql_Connect('127.0.0.1', 3306, 'mydb_test',
'root', '229544','update student_score set name = "大狗" where id = 11')
# test1.conn()
test1.conn()