首页 > 代码库 > python操作MySQL

python操作MySQL

#coding=utf-8
 
import MySQLdb
 
conn = MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘123456‘,charset=‘utf8‘)
cursor = conn.cursor()
try:
    #创建数据库
    DB_NAME = ‘test‘
    cursor.execute(‘DROP DATABASE IF EXISTS %s‘ %DB_NAME)
    cursor.execute(‘CREATE DATABASE IF NOT EXISTS %s‘ %DB_NAME)
    conn.select_db(DB_NAME)
 
    #创建表
    TABLE_NAME = ‘t_user‘
    cursor.execute(‘CREATE TABLE %s(id int primary key,name varchar(30))‘ %TABLE_NAME)
 
    #插入单条数据
    value = http://www.mamicode.com/[1,‘alexzhou1‘]"%s" WHERE id = %s‘ %(TABLE_NAME,‘zhoujianghai‘,1))
    #删除记录
    cursor.execute(‘DELETE FROM %s WHERE id = %s‘ %(TABLE_NAME,2))
 
    #必须提交,否则不会插入数据
    conn.commit()
except:
    import traceback
    traceback.print_exc()
    conn.rollback()
finally:
    cursor.close()
    conn.close()

原文地址: http://codingnow.cn/language/444.html

python操作MySQL