python操做MySQL數據庫

#!/usr/bin/env python
# -*- coding: utf_ -*-

import MySQLdb
import datetime
import time

conn = MySQLdb.connect(
    unix_socket='/tmp/mysql.sock',
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='root',
    db='mytest',
)

 

def operate_test1(id,list):
    aa = int(list[1])
    bb = list[2]
    cc =int( list[7])#string轉int
    dd = list[9]
    sql="insert into test (aa,bb,cc,dd,ee) values ('%d','%s','%d','%s',%d) "%(
        aa,bb,cc,dd,id)
    print sql
    return sql
cur = conn.cursor()
sql = "select * from test"

# 得到表中有多少條數據
a = cur.execute(sql)
print a
info = cur.fetchmany(a)
#info爲多條查詢後的結果,類型爲tuple類型,i爲查詢後的單條結果,類型也爲tuple類型
for i in info:
    sql = operate_test(i)
    # print sql
    cur.execute(sql)
   #conn.insert_id()爲剛插入的數據的id
    print int(conn.insert_id())
    sql=operate_test1(int(conn.insert_id()), ii)
    # print sql
    cur.execute(sql)
cur.close()
conn.commit()
conn.close()
相關文章
相關標籤/搜索