from pymysql import connect
def main():
#第一步创建连接对象
conn = connect(host='192.168.11.93',port=3306,user='root',password='root',db='test2',charset='utf8')
#第二步创建游标对象
cur = conn.cursor()
#构造sql语句
sql = 'select * from stu'
#使用游标对象执行sql语句
cur.execute(sql)
#通过游标对象可以查看查询的结果
#返回的是所有数据,每个数据是一个小元组,然后全部放在一个大元组当中
# a = cur.fetchall()
# 返回的是一个数据,这个数据用元组封装
# a = cur.fetchone()
# cur.scroll(1)
# a = cur.fetchall()
a = cur.fetchmany(3)
a=cur.fetchall()
a=cur.fetchone()
print(a)
cur.close()
conn.close()
if __name__ == '__main__':
main()
上面的方式会造成SQL注入, 需要把SQL参数化传入
from pymysql import connect
class MysqlHandler(object):
def __init__(self,host,port,user,password,db,charset):
self.host = host
self.port = port
self.user = user
self.password = password
self.db = db
self.charset = charset
self.conn = None
self.cur = None
def open(self):
self.conn = connect(host=self.host,port=self.port,user=self.user,password=self.password,db=self.db,charset=self.charset)
self.cur = self.conn.cursor()
def close(self):
self.cur.close()
self.conn.close()
def cud(self,sql,params=None):
if not params:
params=[]
self.cur.execute(sql,params)
self.conn.commit()
self.close()
def get_one(self,sql,params=None):
if not params:
params=[]
self.cur.execute(sql,params)
a = self.cur.fetchone()
self.close()
return a
def get_all(self,sql,params=None):
if not params:
params=[]
self.cur.execute(sql,params)
a = self.cur.fetchall()
self.close()
return a
def main():
helper = MysqlHandler('192.168.11.96',3306,'root','root','test2','utf8')
helper.open()
helper.cud("insert into student---------",params=[])
print('ok')
if __name__ == '__main__':
main()