Getting started with Python (4) connecting to MySQL

Source: Internet
Author: User
(1) install MySql in advance. Otherwise, the following pythonsetup. pybuild will prompt that "EnvironmentError: mysql_confignotfound" cannot be found. The installation command is as follows: sudoapt-getinstalllibmysqlclient-devsudoa.

Download MySQL for python, the latest version of mysql-python-1.2.4b4.tar.gz 1) to install in advance: mysql_config; otherwise, follow the python setup. in py build, "EnvironmentError: mysql_config not found" is not found. The installation command is as follows: sudo apt-get install libmysqlclient-dev sudo.

Download MySQL for Python, the latest MySQL-python-1.2.4b4.tar.gz


1) install MySql in advance

Otherwise, "EnvironmentError: mysql_config not found" is not displayed in the python setup. py build. The installation command is as follows:

Sudo apt-get install libmysqlclient-dev

Sudo apt-get install python-dev (solve fatal error: Python. h: No such file or directory)

CentOS install yum install mysql-devel and yum install python-devel (Solve error: command 'gcc 'failed with exit status 1)


2) then install MySQLdb.

$ Tar zxvf MySQL-python-1.2.2.tar.gz
$ MySQL-python-1.2.2 cd
$ Sudo python setup. py build
$ Sudo python setup. py install


3) Verify the installation

Homer @ ubuntu :~ /MyCode/python $ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> Import MySQLdb
>>>

Import MySQLdb has no error. The installation is successful!


Test example:

import MySQLdbdb = MySQLdb.connect("localhost","myusername","mypassword","mydb" )cursor = db.cursor()cursor.execute("SELECT VERSION()")data = cursor.fetchone()    print "Database version : %s " % data    db.close()


Example of connecting python to mysql:

##################### IT-Homer# 2013-05-10####################import MySQLdbdb = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")cursor = db.cursor()cursor.execute("Select * from gameTestDB limit 10")result = cursor.fetchall()for row in result:  #print row  #print row[0], row[1], row[2]  #print '%s, %s, %s' % (row[0], row[1], row[2])  print ', '.join([str(row[0]), str(row[1]), str(row[2])])cursor.close()'''import sysimport MySQLdbreload(sys)sys.setdefaultencoding('utf-8')db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')cur = db.cursor()cur.execute('use testDB')cur.execute('select * from gameTestDB limit 10')f = file("/home/homer/tmp_mysql.txt", 'w')for row in cur.fetchall():  f.write(str(row))  f.write("\n")f.close()cur.close()'''


##################### IT-Homer# 2013-05-10####################import MySQLdb# local mysql# db = MySQLdb.connect(host="localhost", user="root", passwd="abcd1234", db="testDB")# aws rds mysqldb = MySQLdb.connect(host="ithomer.aliyun.com", user="ithomer", passwd="abcd1234", db="dman")cursor = db.cursor()cursor.execute("Select * from score limit 10")result = cursor.fetchall()for row in result:  #print row  #print row[0], row[1], row[2]  #print '%s, %s, %s' % (row[0], row[1], row[2])  print ', '.join([str(row[0]), str(row[1]), str(row[2])])cursor.close()'''import sysimport MySQLdbreload(sys)sys.setdefaultencoding('utf-8')db = MySQLdb.connect(user='root', passwd='abcd1234', charset='utf8')cur = db.cursor()cur.execute('use testDB')cur.execute('select * from gameTestDB limit 10')f = file("/home/homer/tmp_mysql.txt", 'w')for row in cur.fetchall():  f.write(str(row))  f.write("\n")f.close()cur.close()


Connect python to mongodb

1) install pymongo

Pymongo download, latest pymongo-2.6.tar.gz

Install

$ Tar zxvf pymongo-2.6.tar.gz
$ Pymongo-2.6 cd
$ Sudo python setup. py build
$ Sudo python setup. py install


2) connect to mongodb

#!/usr/bin/pythonimport pymongoimport randomHOST = '172.27.22.21'PORT = 27017_DB='test'_TABLE='testuser'conn = pymongo.Connection("172.27.22.21", 27017)db = conn[_DB]  # get dbdb.authenticate("yanggang", "123456")table = db[_TABLE]      # get collectiontable.drop()table.save({"id":1, "name":"homer", "age":18})for id in range(2,10):  name = random.choice(['it', 'homer', 'sunboy', 'yanggang'])  age = random.choice([10, 20, 30, 40, 50, 60])  table.insert({"id":id, "name":name, "age":age})cursor = table.find()for user in cursor:  print user'''conn = pymongo.Connection("172.27.22.21", 27017)db = conn.testdb.authenticate("yanggang", "123456")db.testuser.drop()db.testuser.save({"id":1, "name":"homer", "age":18})for id in range(2,10):  name = random.choice(['it', 'homer', 'sunboy', 'yanggang'])  age = random.choice([10, 20, 30, 40, 50, 60])  db.testuser.insert({"id":id, "name":name, "age":age})cursor = db.testuser.find()for user in cursor:  print user'''

Running result




Connect python to Redis

1) Go to redis-py to download the release version release, the latest release version: redis-py-2.8.0.zip

2) unzip redis-py-2.8.0.zip: unzip redis-py-2.8.0.zip, install: sudo python setup. py install

3) Verify that the installation is successful:

# Python
>>> Import redis
>>>

4) simple example:

>>> import redis>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)>>> r.set('foo', 'bar')True>>> r.get('foo')'bar'

5) python script example
#! /Usr/bin/python #-*-coding: UTF-8-*-import sysreload (sys) sys. setdefaultencoding ('utf-8') import redis_REDIS_HOST = '2017. 27.9.104 '_ REDIS_PORT = 62.16_redis_db = 0def read_redis (): r = redis. redis (host = _ REDIS_HOST, port = _ REDIS_PORT, db = _ REDIS_DB) # delete all data in the current database r. flushdb () r. set ('foo', 'bar') print (r. get ('foo') # bar r. set ('blog ', 'ithomer.. net ') r. set ('name', 'hangzhou') # If no key is found, None print (r. get ('one123') # None # print (r. dbsize () #3 # list all key values print (r. keys () # ['blog ', 'foo', 'name'] if _ name _ = "_ main _": read_redis ()
Running result:

Bar
None
3
['Blog ', 'foo', 'name']


Reference recommendations:

Connect Python connector to MySQL

MySQLdb User's Guide

Python string operations

Mysql_config not found (stackover flow)


Create a mysql database using python

Connect to and operate mongodb using python

Redis-py (github)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.