zoukankan      html  css  js  c++  java
  • python连接mysql数据库


    安装 python 连接MySQL数据库的模块:
    3.x : MySQL-python (pymysql)
    2.x : PyMySQL (MySQLdb)

    2.x 安装:
    报错:
    pip install MySQL-python
    error: command 'gcc' failed with exit status 1
    解决:
    yum install -y python-devel
    pip install MySQL-python

    3.x安装:
    pip install PyMySQL

    pip安装的模块会把模块放在
    pip3安装的模块




    查数据实例代码:

    import pymysql as sql
    con = sql.connect(
    host = "192.168.100.20", #host 主机,本机的主机名或者ip,指你连接的数据库的主机
    user = "fxh", #user 登录数据库的用户名称
    passwd="123456", #passwd 登录数据库用户名称对应的密码
    db="t1", #你要操作的数据库的名称
    charset="utf8"
    )
    #实例化mysql游标
    #游标:是用来传递python对mysql的命令和接收mysql返回给python的数据的对象
    cur = con.cursor()
    #利用游标执行数据库命令
    cur.execute("select * from student") #返回值是受影响的行数
    #接收数据库的返回
    all_data=cur.fetchall() #接收所有的返回 , 数据已经在内存中了,拿多拿少没多大意义!
    cur.scroll(0,mode='absolute') # 这里有个和文件操作类型的指针问题,指针回到开始的点。
    cur.scroll(1,mode='relative') # 当前位置往下走一行
    one_data=cur.fetchone() #接收返回的1条
    select_data=cur.fetchmany(2) #接收返回的指定条(取2条)
    #print(all_data) #返回值是一个大元祖中包含多个元祖,每个元祖是一行
    #print(one_data)
    #print(select_data)
    cur.close() #关闭游标
    con.commit()              #提交对数据库的操作
    con.close()               #关闭数据库连接



    插入数据 实例代码:

    import pymysql as sql
    con = sql.connect(
    host = "192.168.100.20",
    user = "fxh",
    passwd="123456",
    db="t1",
    charset="utf8"
    )
    cur = con.cursor()
    r=cur.execute("insert into student(gender,class_id,sname) values(%s,%s,%s)",("男",1,"fxh"))
    r1=cur.executemany("insert into student(gender,class_id,sname) values(%s,%s,%s)",(("男",1,"fxh2"),("男",1,"fxh1")))
    print(r,r1)
    cur.close()
    con.commit()
    con.close()

    #字符串拼接执行sql (不使用,有sql注入的风险)
    #传递参数形式执行sql
    # execute("sql语句","传入的参数。多个参数用元祖。")
    # executemany("sql语句",传入多条values时:在一个可迭代对象中放多个元祖)


    使用返回为字典形式的游标:
    import pymysql
    import pymysql.cursor

    cur = con.cursor(cursor=pymysql.cursors.DictCursor)

    #最终返回的数据类似:
    [{'gender': '男', 'sname': '刘四1', 'class_id': 3, 'sid': 32}, {'gender': '男', 'sname': 'fxh', 'class_id': 1, 'sid': 33}, {'gender': '男', 'sname': 'fxh', 'class_id': 1, 'sid': 34}, {'gender': '男', 'sname': 'fxh2', 'class_id': 1, 'sid': 35}, {'gender': '男', 'sname': 'fxh1', 'class_id': 1, 'sid': 36}]

    获取当前自增id:
    cur.lastrowid






  • 相关阅读:
    如何实现shell并发 一个入门级可控多线程shell脚本方案
    Android SDK 开发指南
    Android SDK上手指南:知识测试
    JavaScript apply
    chrome 调试
    jQuery file upload上传图片出错分析
    jQuery插件开发
    yarn
    What is 'typeof define === 'function' && define['amd']' used for?
    jQuery .closest()
  • 原文地址:https://www.cnblogs.com/fanxuanhui-linux/p/6185010.html
Copyright © 2011-2022 走看看