zoukankan      html  css  js  c++  java
  • python MySQLdb的操作

    1.import MySQLdb;

    2.与mysql数据库建立连接:con=MySQLdb.connect(user='root',db='mysql',passwd='dingjia',host='localhost')

    3.当没有游标cursor对象时候,连接对象可以使用query()方法,执行sql查询

     con.query('create database test')

    4.使用游标对象和execute()方法来执行sql

    cur=con.cursor()  返回游标对象

    cur.execute('create table users(login varchar(8),uid INT)')

    cur.execute('insert into users values('hzhida',1000)')

    cur.execute('select *from users')

    for data in cur.fetchall(): 输出查询结果得到的数据

      print '%s\t%s' % data

    cur.close()  关闭游标

    con.commit()  提交事务

    con.close()     关闭连接

    python cookbook 的例子:

    #-*-coding:utf-8-*-
    import MySQLdb,cPickle
    
    #连接到数据库,并获得图标
    connection = MySQLdb.connect(user = 'root',db='zm',passwd = '36039975',host='localhost')
    cursor = connection.cursor()
    
    #创建一个新表以用于试验
    cursor.execute('create table test(name TEXT, ablob BLOB)')
    
    try:
        #准备一些BLOB用于测试
        names = 'aramis', 'athos','porthos'
        data = { }
        for name in names:
            datum = list(name)
            datum.sort()
            data[name] = cPickle.dumps(datum,2)
        #execute insert
        sql = "insert into test values(%s, %s)"
        for name in names:
            cursor.execute(sql,(name,MySQLdb.escape_string(data[name])))
        #check in the database
        sql = "select name, ablob from test order by name"
        cursor.execute(sql)
        for name , blob in cursor.fetchall():
            print name, cPickle.loads(blob), cPickle.loads(data[name])
    
    finally:
        #finish,delete table and close connection
        cursor.execute("drop table test")
        cursor.close()
        connection.close()
    输出:

    aramis ['a', 'a', 'i', 'm', 'r', 's'] ['a', 'a', 'i', 'm', 'r', 's']
    athos ['a', 'h', 'o', 's', 't'] ['a', 'h', 'o', 's', 't']
    porthos ['h', 'o', 'o', 'p', 'r', 's', 't'] ['h', 'o', 'o', 'p', 'r', 's', 't']

  • 相关阅读:
    时间处理得到UTC时间
    java数据同步陷阱
    360公司2016笔试题
    YTU 1439: 2.4.5 Fractions to Decimals 分数化小数
    YTU 2422: C语言习题 n个数逆序
    YTU 2421: C语言习题 矩形法求定积分
    YTU 2427: C语言习题 整数排序
    YTU 2832: 使用指针访问数组元素--程序填空
    YTU 1050: 写一个函数,使给定的一个二维数组(3×3)转置,即行列互换
    HDU 1069:Monkey and Banana
  • 原文地址:https://www.cnblogs.com/hzhida/p/2619848.html
Copyright © 2011-2022 走看看