• python操作mysql


    python连接上数据库,进行非原生操作

    数据库简单的增删改查可见我前面的随笔

     1 import pymysql
     2 conn = pymysql.connect(     # 建立连接
     3     host='localhost',    #地址
     4     port=3306,      #端口(未修改默认就是3306)
     5     user='xxxxx',    # 用户
     6     password='xxxxx',    # 用户密码
     7     db='spiders',     # 需操作的库名
     8     charset='utf8'  # 编码,不能写成'utf-8'
     9 )
    10 cur = conn.cursor()     # 建立游标
    11 cur.execute('show tables')    # 转换为数据库可读的函数(查看所有的表)
    12 data = cur.fetchall()    # 获取操作结果fetchone()表示获取一条结果
    13 print(data)    # 输出结果(结果是一个元组,可用拆包工具‘*’拆包)

    查比较简单,增删改操作涉及数据库的事务,python下的增删改解释器会自动创建一个事务,对于所有的增删改操作

    都要进行提交(commit).类似于转账是的确认操作,没有提交,钱是不会转移的

    sql = '''create table if not exists class(    #sql语句:创建一个名为class的表格
            id int primary key auto_increment,   # 主键id,自增长约束
            name varchar(20) not null        # name  非空约束
            )
            '''
    cur.execute(sql)    # 将整句sql语句放入,注意此时数据库并没有生成这张表格,因为还未提交
    sql1 = "insert into class values(3,'wjh'),(4,'zy')"    # sql语句 插入数据
    try:    # 异常处理
        cur.execute(sql1)
        conn.commit()    # 增删改操作都要向mysql表示提交操作
    except:    # 如果操作出错,进行回滚操作
        cur.execute('rollback')    # 撤销
    a = cur.execute('show tables')
    b = cur.fetchall()     # 获取上一条操作的结果
    print('表数量:', a)
    print('表名:', *b)
    cur.execute('select * from class')    # 查看student表的全部内容
    c = cur.fetchall()
    print('class内容:', *c)
    cur.close() # 关闭游标
    conn.close()    # 关闭连接    
  • 相关阅读:
    JS 、JQ 获取宽高总结 & JS中getBoundingClientRect的作用及兼容方案
    JS与JQ 获取页面元素值的方法和差异对比
    ES6
    移动端:active伪类无效的解决方法
    JavaScript中valueOf函数与toString方法
    Reverse Words in a String -- LeetCode
    Count Primes -- LeetCodes (primality test)
    Maximum Size Subarray Sum Equals k -- LeetCode
    Subsets II -- LeetCode
    Maximum Product of Word Lengths -- LeetCode
  • 原文地址:https://www.cnblogs.com/pywjh/p/9408430.html
Copyright © 2020-2023  润新知