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 -*-
  • 相关阅读:
    负margin实现div的左右排版
    一起来灭掉IE6!
    javac编译多个带package文件
    iis express感觉还不错
    关于sqlite使用entity framework的布署问题
    远程服务器返回了错误 NOTFOUND
    userAgent string detection in javascript
    a crossbroswer solution for parse xml fragment
    event related object in javascript
    several way to implement inheritance in javascript
  • 原文地址:https://www.cnblogs.com/seablog/p/7136665.html
Copyright © 2011-2022 走看看