zoukankan      html  css  js  c++  java
  • Python连接mysql基本操作

    创建数据库表

    import  pymysql
    
    # 打开数据库连接
    db= pymysql.connect(host='localhost',user="root",password="root",db="ceshi",port=3306,charset='utf8')
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    # 使用execute方法执行SQL语句
    cur.execute("drop table if exists student")
    sql = "create table student(id  int primary key auto_increment ,name char(20),sex char(1),age int)"
    try:
        # 执行sql语句
        cur.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        db.rollback()
    # 关闭数据库连接
    db.close()

    数据库查询操作

    import  pymysql
    
    db= pymysql.connect(host='localhost',user="root",password="root",db="ceshi",port=3306,charset='utf8')
    cur = db.cursor()
    sql = "select * from student "
    
    try:
        cur.execute(sql)
        result = cur.fetchall()
        for row in result:
            id = row[0]
            name = row[1]
            sex = row[2]
            age = row[3]
            print(id ,name ,sex,age)
    finally:
        db.close()

    数据库插入操作

    import  pymysql
    
    # 打开数据库连接
    db= pymysql.connect(host='localhost',user="root",password="root",db="ceshi",port=3306,charset='utf8')
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    # 使用execute方法执行SQL语句
    sql ="INSERT INTO student(name,sex,age) values('mac',1,222)"
    
    try:
        # 执行sql语句
        cur.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        db.rollback()
    # 关闭数据库连接
    db.close()

    数据库更新操作

    import  pymysql
    
    # 打开数据库连接
    db= pymysql.connect(host='localhost',user="root",password="root",db="ceshi",port=3306,charset='utf8')
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    # 使用execute方法执行SQL语句
    sql ="update student set age = 123 where age = 222"
    
    try:
        # 执行sql语句
        cur.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        db.rollback()
    # 关闭数据库连接
    db.close()

    删除操作

    import  pymysql
    
    # 打开数据库连接
    db= pymysql.connect(host='localhost',user="root",password="root",db="ceshi",port=3306,charset='utf8')
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    # 使用execute方法执行SQL语句
    sql ="delete from student where age > 50"
    
    try:
        # 执行sql语句
        cur.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        db.rollback()
    # 关闭数据库连接
    db.close()
  • 相关阅读:
    初识Vulkan
    网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求
    Hello,Android
    熊猫猪新系统測试之四:Ubuntu 14.04
    iOS OC08,09_内存管理
    XML总结
    【Scala-ML】怎样利用Scala构建并行机器学习系统
    在vs2010中编译log4cxx-0.10.0具体方法(从下载、编译、解决错误具体介绍)
    UI_UITableView_搭建
    Angular 4 子路由
  • 原文地址:https://www.cnblogs.com/zhan1995/p/8926419.html
Copyright © 2011-2022 走看看