• 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






  • 相关阅读:
    51nod 1621 花钱买车牌 优先队列
    最大字段和 51nod 1049 水水水水水水水水水水水水
    大数相乘 51nod 1027 水题
    逆序数 51nod 1019 归并 分治
    最长公共子序列 LCS 递归 dp 51Nod 1006
    vc6 字体设置
    自行车维护大全(zz)
    DirectX 9.0 3D游戏开发编程基础 [书评](zz)
    二维线段树
    latex 引用文献 bib
  • 原文地址:https://www.cnblogs.com/fanxuanhui-linux/p/6185010.html
Copyright © 2020-2023  润新知