您的位置:首页 > 运维架构 > Linux

CentOS下安装python-mysqldb

2016-02-02 22:21 471 查看
1、# yum install python-devel mysql-devel zlib-devel openssl-devel

2、http://pypi.python.org/pypi/MySQL-python/#downloads 下载安装包

# wget http://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.3.tar.gz
3、http://pypi.python.org/pypi/setuptools#downloads
下载工具

# wget http://pypi.python.org/packages/2.4/s/setuptools/setuptools-0.6c11-py2.4.egg
4、先安装工具

# sh setuptools-0.6c11-py2.4.egg

# python

>>> import setuptools

不提示错误表示成功

5、安装 MySQL-python-1.2.3.tar.gz

# tar -zxvf MySQL-python-1.2.3.tar.gz

# cd MySQL-python-1.2.3

# vi setup_posix.py

找到mysql_config.path 一行,改为mysql_config.path = "/usr/bin/mysql_config"

# python setup.py build

# python setup.py install

# python

>>> import MySQLdb

不提示错误表示成功

Python 操作数据库 连接创建库:

[python] view
plain copy

#! /usr/bin/env python

import MySQLdb

conn = MySQLdb.connect(host='localhost',user='root',passwd='root',charset='utf8')

cursor = conn.cursor()

#Crete Database

#cursor.execute("""create database python """)

#Select Database

conn.select_db('python');

#Create Table

#cursor.execute("""create table gaiqi(id int(4),info varchar(100)) """)

#Insert data

#value = [1,"inserted"];

#cursor.execute("insert into test values(%s,%s)",value);

#Insert more

values=[]

for i in range(20):

values.append((i,'Hello Mysqldb'+str(i)))

cursor.executemany("""insert into test values(%s,%s)""",values);

cursor.close();

查询记录

[python] view
plain copy

#! /usr/bin/env python

import MySQLdb

conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='python',charset='utf8')

cursor = conn.cursor()

count = cursor.execute('select * from test')

print 'All Total %s',count

#Get 1 Result

result = cursor.fetchone();

print result

print 'ID:%s inof:%s'% result

#Get 5 Result

results = cursor.fetchmany(5)

for r in results:

print r

#Get All Result

res = cursor.fetchall()

for r in res:

print r

cursor.close();

插入时间:

[python] view
plain copy

import time

print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

备份文件:

[python] view
plain copy

#! /usr/bin/env python

import os

import time

source = ['/var/www/html','/var/test']

target_dir = '/mnt/backup/'

target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip'

today = target_dir+ time.strftime('%Y%m%d')

now = time.strftime('%H%M%S')

if not os.path.exists(today):

os.mkdir(today)

print 'Dir OK',today

target = today+os.sep+now+'.zip'

zip_command = "zip -qr '%s' %s" % (target,' '.join(source))

if os.system(zip_command) == 0:

print 'Success Backup to',target

else:

print 'Failed Backup'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: