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

    python安装pymysql模块

    实例一:

    import  pymysql
    #建立数据库连接
    db=pymysql.connect(host='192.168.59.128',user='root1',passwd='123456',db='test',port=3306)
    #使用cursor()方法获取操作游标
    cursor=db.cursor()
    # 使用execute方法执行SQL语句
    cursor.execute("select version()")
    # 使用 fetchone() 方法获取一条数据
    data = cursor.fetchone()

    print("Database version : %s " % data)

    # 关闭数据库连接
    db.close()

    结果:Database version : 5.6.16 

    对数据查询操作
    import pymysql

    db=pymysql.connect(host='192.168.59.128',user='root1',passwd='123456',db='test',charset='utf8')

    cursor=db.cursor()
    sql="select * from students"
    try:
    cursor.execute(sql)
    #获取全部的数据
    results=cursor.fetchall()
    print(results)
    #遍历结果集
    for row in results:
    id=row[0]
    name=row[1]
    sex=row[2]
    age=row[3]
    classes=row[4]
    addr=row[5]
    print(id,name,sex,age,classes,addr)
    except:
    print("can not find the table")

    db.close()

    增删改操作
    import pymysql

    db=pymysql.connect("192.168.59.128",'root1','123456','test',charset="utf8")
    cursor=db.cursor()
    #sql="insert into students VALUES (1009,'张飞','男',30,'白胡子','上海')"
    #sql="update students set name='皇马' where id=801"
    sql="delete from students where id=1009"
    try:
    cursor.execute(sql)
    #数据发生改动需要commit
    db.commit()
    except:
    #如果执行不成功数据回滚
    db.rollback()
    db.close()




  • 相关阅读:
    利用JNI技术在Android中调用、调试C++代码
    iOS在线更新framework,使用NSBundle动态读取
    CocoaPods pod install
    Quartz 2D在ios中的使用简述二:创建画布
    iOS并发编程笔记【转】
    openCV C++ 代码笔记
    Quartz 2D在ios中的使用简述一:坐标体系
    ios视频播放器,代码和界面分离
    mac显示和隐藏文件
    3点画圆
  • 原文地址:https://www.cnblogs.com/zzzao/p/9177838.html
Copyright © 2011-2022 走看看