zoukankan      html  css  js  c++  java
  • Python【pymysql】模块

    import pymysql
    # 1、连上数据库 账号、密码 ip 端口号 数据库
    #2、建立游标
    #3、执行sql
    #4 、获取结果
    # 5、关闭游标
    #6、连接关闭
    coon = pymysql.connect(
    host='127.0.0.1',user='jxz',passwd='123456',
    port=3306,db='jxz',charset='utf8'
    #port必须写int类型,
    #charset这里必须写utf8,不能写utf-8,写utf-8会报错
    #写成username是错误的,必须写成user
    )
    cur = coon.cursor() #建立游标
    # cur.execute('select * from stu;')#执行sql语句
    cur.execute('insert into stu (id,name,sex) VALUE (1,"牛寒阳","女");')
    # delete update insert必须commit,select不需要commit
    coon.commit() #必须得commit
    res = cur.fetchall() #获取所有返回的结果
    print(res)
    cur.close()#关闭游标
    coon.close()#关闭连接

    print("================分隔代码块=============")
    #https://www.cnblogs.com/tkqasn/p/6001134.html
    def my_db(host,user,passwd,db,sql,port=3306,charset='utf8'):
    import pymysql
    coon = pymysql.connect(user=user,
    host=host,
    port=port,
    passwd=passwd,
    db=db,
    charset=charset
    )
    cur = coon.cursor() #建立游标
    cur.execute(sql)#执行sql
    if sql.strip()[:6].upper()=='SELECT':
    res = cur.fetchall() #返回的结果是一个二维元组
    else:
    coon.commit()
    res = 'ok'
    cur.close()
    coon.close()
    return res
  • 相关阅读:
    Redis数据库
    python的web运用
    python对 if __name__=='__main__'的理解
    python的函数
    python的四种内置数据结构
    python的循环和选择
    关于oracle设置主键自增的问题
    用HttpClient和用HttpURLConnection做爬虫发现爬取的代码少了的问题
    ORACLE not available如何解决
    集合(下)
  • 原文地址:https://www.cnblogs.com/mtszw/p/9022047.html
Copyright © 2011-2022 走看看