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 操作数据库 连接创建库:
#! /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();
#! /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();
import time print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
备份文件:
#! /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'