zoukankan      html  css  js  c++  java
  • python mysql基本操作

    1.创建数据库、表添加数据。

    # -*- coding: utf-8 -*-
    import MySQLdb.cursors
    conn =MySQLdb.connect('127.0.0.1','root','123456',charset = 'utf8')
    cur = conn.cursor()  ##得到游标
    
    cur.execute('create database if not exists python')##创建数据库
    conn.select_db('python')
    cur.execute('create table if not exists test(id int,info varchar(20))')##创建表
    
    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)  #添加一条数据
    values=[]
    for i in range(2,20):
        values.append((i,'hi rollen'+str(i)))
    cur.executemany('insert into test values(%s,%s)', values)  ##添加多条数据
    
    conn.commit()  ##提交事务
    cur.close()
    conn.close()

    2.修改、删除数据库操作

    # -*- coding: utf-8 -*-
    
    import MySQLdb.cursors 
    conn =MySQLdb.connect('127.0.0.1','root','123456',charset = 'utf8')
    conn.select_db('python')
    cur = conn.cursor()  ##得到游标
    
    cur.execute('update test set info="I am rollen" where id=3')  ##修改数据
    cur.execute('delete from test where id = 1')  ##删除数据
    
    conn.commit()  ##提交事务
    cur.close()
    conn.close()

    3.查询数据库

    # -*- coding: utf-8 -*-
    import MySQLdb.cursors
    conn =MySQLdb.connect('127.0.0.1','root','123456',charset = 'utf8')
    cur = conn.cursor()  ##得到游标
    
    conn.select_db('python')  ##选择数据库
    cur.execute('select * from test')
    results = cur.fetchall()  ##获得所有查询结果
    for row in results:
        rid = row[0]
        info = row[1]
        print "id=%s,info=%s" % (rid, info)
    cur.close()
    conn.close()
    # -*- coding: utf-8 -*-
  • 相关阅读:
    基于2.0 创建旧模板项目
    vue 脚手架 图形化界面操作
    webpack 相关配置 (1)
    ES6模块化 babel
    处理时间函数
    问题集-- SQL 约束名不能重复
    SQL 必知必会-- 第17课:创建和操作表
    SQL 必知必会-- 第1课:数据库基础和什么是SQL
    Java SE ---类,方法,对象等
    Java SE ---控制流程:break与continue语句
  • 原文地址:https://www.cnblogs.com/seablog/p/7136665.html
Copyright © 2011-2022 走看看