CentOS下安装python-mysqldb

来源:互联网 发布:2017笔记本清理软件 编辑:程序博客网 时间:2024/06/08 21:02

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 pythonimport MySQLdbconn = MySQLdb.connect(host='localhost',user='root',passwd='root',charset='utf8')cursor = conn.cursor()#Crete Database#cursor.execute("""create database python """) #Select Databaseconn.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 morevalues=[]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 pythonimport MySQLdbconn = 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 Resultresult = cursor.fetchone();print resultprint 'ID:%s  inof:%s'% result#Get 5 Resultresults = cursor.fetchmany(5)for r in results:  print r#Get All Resultres = cursor.fetchall()for r in res:  print r    cursor.close();

插入时间:

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

备份文件:

#! /usr/bin/env pythonimport osimport timesource = ['/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',todaytarget = today+os.sep+now+'.zip'zip_command = "zip -qr '%s' %s" % (target,' '.join(source))if os.system(zip_command) == 0:  print 'Success Backup to',targetelse:  print 'Failed Backup'