操作mysql数据库

一、操作mysql数据库

conn = pymysql.connect()  连接数据库,括号内写host(数据库ip)、user(用户名)、password(密码)、port(端口)、db(数据库名称)。括号内若写入autocommit=Ture,便不许手动提交,会自动提交

cur = conn.cursor()  建立游标

cur.execute() 执行sql语句

conn.commit() 提交修改信息

cur.fetchall() 获取查询到的所有结果

cur.fetchone() 只获取到一条结果

cur.fetchmany(2) 获取到指定的几条结果

cur.close() 游标关闭

conn.close() 连接关闭

# 1、连上数据库  ip 账号 密码 端口号 数据库名
# 2、执行sql
# 3、获取到结果

import pymysql
conn = pymysql.connect(host='******(ip)',user='jxz',password='123456',
                port=3306,db='jxz',charset='utf8',autocommit=True)# 加上autocommit后,便不需手动提交,会自动提交

cur = conn.cursor()# 建立游标
# cur.execute('select * from nhy;')# 执行sql语句,它只是帮你执行sql语句,不会给你返回数据
# sql = 'insert into nhy(name,pwd) value ("aaa","222222")'
# cur.execute(sql)
# conn.commit()
cur.execute('select * from nhy where name="aaa"')


# sql2 = 'select * from nhy where name="aaa"'

print(cur.fetchall())# 获取查询到的所有结果
# print(cur.fetchone()) # 只获取一条
# print(cur.fetchmany(2))# 指定获取几条
cur.close()#游标关闭
conn.close()#连接关闭
# 'select' # 'update' # 'delete' # 'insert'

使用函数实现操作数据库:

import pymysql

def my_db(ip,user,passwd,db,sql,port=3306,charset='utf8'):
    coon = pymysql.connect(host=ip,user=user,
                    password=passwd,db=db,
                    port=port,charset=charset,autocommit=True)
    cur = coon.cursor()
    sql=sql.strip()
    cur.execute(sql)
    sql_start = sql[:6].lower()#取sql的开头,转成小写
    if sql_start.startswith('select') or sql_start.startswith('show'):
        data = cur.fetchall()
    else:
        data = 'ok'
    cur.close()
    coon.close()
    return data

my_db(ip='***.***.***.***',user='jxz',passwd='123456',db='jxz',sql='select * from nhy where name="xiaobai";')

 二、操作mysql数据库、写入xls表格

import pymysql,xlwt
coon = pymysql.connect(host='******(ip)',user='jxz',password='123456',db='jxz',port=3306,charset='utf8')
# cur = coon.cursor(cursor=pymysql.cursors.DictCursor) #指定游标类型
cur = coon.cursor() #指定游标类型
cur.execute('select * from YUZE_userinfo;')

fileds = [ filed[0] for filed in cur.description ] #获取到所有的字段
#列表生成式
data = list(cur.fetchall())
data.insert(0,fileds) #只是给你加数据
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')

line = 0 #行号
for d in data:#外层循环控制行,
    # ['id','name','sex']
    col = 0  # 列号
    for col_data in d:  #控制列
        sheet.write(line,col,col_data)
        col+=1
    line+=1

#比较高端
for index,line_data in enumerate(data):
    #0,['id','name','sex']
    #1,[1,nhy,nan]
    for index2,col_data in enumerate(line_data):
        #0,1
        #1,nhy
        #2,nan
        sheet.write(index,index2,col_data)
        #0,0,id
        #0,1,name
        #0,2sex

#1、一个一个单元格写,先写第一行的每个单元格
#2、写每一行的时候,行号是不变的,列在变
#3、嵌套的循环

# book.save('user.xls')
# cur.close()
# coon.close()
#
原文地址:https://www.cnblogs.com/Noul/p/9294169.html