您的位置:首页 > 编程语言 > Python开发

Install MySQL-python to connect MySQL

2015-01-25 00:00 281 查看
# yum -y install MySQL-python

运行上面的命令即可安装centos7自带的rpm安装包,但是默认的是为python2.*安装



连接MySQL小Demo





#-*- encoding:UTF-8 -*-
import os, sys, string
import MySQLdb

try:
    conn = MySQLdb.connect(host="localhost", user="root", passwd="123456",db="mydatabase")
except Exception, e:
    print e;
    sys.exit()

#Get cursor obj to operator database
cursor = conn.cursor()
sql = "create table if not exists test(name varchar(128) primary key, age int(3))"
cursor.execute(sql)

#insert data to db
sql = "insert into test(name, age) values ('%s', %d)" % ("coode", 25)
sql2 = "insert into test(name, age) values ('%s', %d)" % ("Ben", 19)
try:
    cursor.execute(sql)
    conn.commit();
    cursor.execute(sql2)
    conn.commit()
except Exception, e:
    print e

#select data from db
sql = "select * from test"
cursor.execute(sql)
result = cursor.fetchall()
#the result is a list
if result:
    for rs in result:
        print rs[0], rs[1]

cursor.close()
conn.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐