zoukankan      html  css  js  c++  java
  • python mysql

    写操作:

    #安装PyMySQL:pip3 install PyMySQL
    #!/usr/bin/python3
    #coding=utf-8
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
     
    # SQL 插入语句
    sql = """insert into user set name='zzz',pwd='cccdd',insert_time='13241'"""
    try:
       # 执行sql语句
       cursor.execute(sql)
       # 提交到数据库执行
       db.commit()
       #获取自增id
       new_id = cursor.lastrowid  
    except:
       # 如果发生错误则回滚
       db.rollback()
     
    # 关闭数据库连接
    db.close()
    print(new_id)
    
    读操作单条:

    #!/usr/bin/python3
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
     
    # 使用 execute()  方法执行 SQL 查询 
    cursor.execute("select * from user")
     
    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
     
    print (data)
     
    # 关闭数据库连接
    db.close()
    读操作多条:

    #!/usr/bin/python3
     
    import pymysql
     
    # 打开数据库连接
    db = pymysql.connect("localhost","root","root","mypython" )
     
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
     
    # SQL 查询语句
    sql = "SELECT * FROM user 
           WHERE id > '%d'" % (0)
    try:
       # 执行SQL语句
       cursor.execute(sql)
       # 获取所有记录列表
       results = cursor.fetchall()
       print (results)
    except:
       print ("Error: unable to fetch data")
     
    # 关闭数据库连接
    db.close()
    [{'id': 1, 'insert_time': 2147483647, 'pwd': 'ccc', 'name': 'zsc'}, {'id': 2, 'insert_time': 13241, 'pwd': 'cccdd', 'name': 'zzz'}]



  • 相关阅读:
    对xml的操作使用的类XElement的使用
    在js和C#中split应用和去除字符串分组后的空值
    C# 预定义语言
    C# 中利用 Conditional 定义条件方法
    快速结束占用端口
    详解C++中命名空间的意义和用法
    Template、ItemsPanel、ItemContainerStyle、ItemTemplate
    C++入门(2)
    C++入门(1)
    VS中的配置管理器
  • 原文地址:https://www.cnblogs.com/fonyer/p/8871449.html
Copyright © 2011-2022 走看看