zoukankan      html  css  js  c++  java
  • python操作MySQL数据库

    pip install pymysql
    import pymysql

    connt=pymysql.connect(host='118.24.3.40',user='jxz',password='123456',
    port=3306,db='jxz',charset='utf8',autocommit=True)
    cur=connt.cursor()#建立游标
    # cur.execute('select * from nhy;')#执行sql,没有返回结果
    sql='insert into nhy(name,password) value("xuzhongtao","1234567");'
    cur.execute(sql)
    # connt.commit()
    cur.execute('select * from nhy where name="xuzhongtao";')
    print(cur.fetchall())#获取查询到的所有结果
    # print(cur.fetchone())#只获取一条
    # print(cur.fetchmany(2))#指定获取几条
    cur.close()#游标关闭
    connt.close()#关闭连接
    def my_db(ip,user,passwd,db,sql,port=3306,charset='utf8'):
    conn=pymysql.connect(host=ip,user=user,
    password=passwd,db=db,
    port=port,charset=charset,autocommit=True)
    cur=conn.cursor()
    cur.execute(sql)
    sql=sql.strip()
    sql_start=sql[:6].lower()
    if sql_start.startswith('select') or sql_start.startswith('show'):
    data=cur.fetchall()
    else:
    return 'ok'
    cur.close()
    conn.close()
    return data
    ----------------------------------------------------------------------------------------------
    import pymysql
    import xlwt

    conn=pymysql.connect(host='118.24.3.40',user='jxz',password='123456',db='jxz',port=3306,charset='utf8',autocommit=True)
    cur=conn.cursor()
    # cur=conn.cursor(cursor=pymysql.cursors.DictCursor)#指定游标类型
    cur.execute('select * from app_student limit 10;')
    # print(cur.description)#表的信息
    fildes=[filed[0] for filed in cur.description]#获取到所有的字段
    # print(fildes)
    data=list(cur.fetchall())#data只是给你假数据,并不会返回数据
    data.insert(0,fildes)
    print(data)
    book=xlwt.Workbook(encoding='utf-8')
    sheet=book.add_sheet('sheet1')#
    line=0#行号
    for d in data:
    col = 0 # 列号
    for col_data in d:
    sheet.write(line,col,col_data)
    col+=1
    line+=1
    # for index,line_data in enumerate(data):
    # #['id','name','sex']
    # for index2,col_data in enumerate(line_data):
    # #0,id
    # #1,name
    # sheet.write(index,index2,col_data)
    # #0,0,id
    book.save('nhy.xls')


    # print(cur.fetchall())
    cur.close()
    conn.close()
  • 相关阅读:
    jq:翻页时,保存上页多选框checkbox选中状态
    SpringMVC日期类型转换问题处理方法归纳
    SpringMVC的Date与String互转
    使用AJAX异步提交表单的几种方式
    ORACLE——日期时间格式化参数详解 之三
    ORACLE——日期时间格式化参数详解 之一
    ORACLE——日期时间格式化参数详解 之二
    Json-lib 进行java与json字符串转换之二
    Json-lib 进行java与json字符串转换之一
    java继承-子类调用父类的方法中包含子类重写的方法
  • 原文地址:https://www.cnblogs.com/xuzhongtao/p/11295855.html
Copyright © 2011-2022 走看看