import pymysql
连接数据库方法1:
ip ="192.168.xx.xx"
user = 'jxz'
password="123456"
db='jxz'
port=3306
charset='utf8'
conn = pymysql.connect(host=ip,user=user,password=password,db=db,port=port,charset=charset,autocommit=True) #建立连接
cur = conn.cursor(pymysql.cursors.DictCursor) # 游标(输出的是个字典形式)
sql = 'select * from app_myuser limit 5;'
cur.execute(sql) # 执行sql语句,insert 、update 、delete
all = cur.fetchall() # 打印全部,打印出来的是一个列表
one = cur.fetchone() # 打印一行,打印出来的是一个字典
many = cur.fetchmany(2) # 输入几行打印几行
cur.close() # 关闭游标
conn.close() # 关闭链接
print(one)
print(many)
print(all)
连接数据库方法2:
def op_mysql(sql):
db_info = {'user': 'jxz', 'password': '123456','host': '192.168.xx.xx', 'db': 'jxz', 'port': 3306, 'charset': 'utf8','autocommit': True}
conn = pymysql.connect(**db_info) # 建立连接
cur = conn.cursor(pymysql.cursors.DictCursor) # 游标
cur.execute(sql) # 执行sql语句,insert 、update 、delete
result = cur.fetchall()
cur.close()
conn.close()
return result
op_mysql('select * from app_myuser limit 5')