码迷,mamicode.com
首页 > 数据库 > 详细

python---连接MySQL第二页

时间:2015-11-05 12:01:03      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

用python向MySQL插入值、并取出被插入行的主键。

#!/usr/bin/python
#!coding:utf-8

import mysql.connector
from mysql.connector import errorcode

def insert_data(**kwargs):
    config={
    ‘host‘:kwargs.get(‘host‘,‘127.0.0.1‘),
    ‘port‘:kwargs.get(‘port‘,3306),
    ‘user‘:kwargs.get(‘user‘,‘admin‘),
    ‘password‘:kwargs.get(‘password‘,‘131417‘)
    }
    cnx=None
    cursor=None
    rowid=None
    try:
        cnx = mysql.connector.connect(**config)
        cursor=cnx.cursor()
        cursor.execute(‘insert into studio.t(x) values(2)‘)
        rowid=cursor.lastrowid
        cnx.commit()
    except mysql.connector.Error,err:
        print err
    finally:
        if cursor is not None:
            cursor.close()
            cnx.close()
            print ‘the db resource has been release ...‘

if __name__==‘__main__‘:
    insert_data(host=‘127.0.0.1‘)

 

python---连接MySQL第二页

标签:

原文地址:http://www.cnblogs.com/JiangLe/p/4938899.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!