CentOS 下安装python 之MySQLdb

yum -y install mysql-dev
wget
http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/1.2.4b4/MySQL-python-1.2.4b4.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fmysql-python%2F&ts=1364895531&use_mirror=nchc tar zxvf MySQL-python-1.2.4b4.tar.gz cd MySQL-python-1.2.4b4 python setup.py build python setup.py install

urllib2.URLError: <urlopen error [Errno 110] Connection timed out>
像报了这样的错,多试几次,网络请求超时了

如果 报EnvironmentError: mysql_config not found

版本是2.7.3 

此时执行 find / -name mysql_config 在/usr/bin/下发现了这个文件
然后修改MySQL-python-1.2.3目录下的site.cfg文件
去掉mysql_config=XXX这行的注释,并改成mysql_config=/usr/bin/mysql_config(以mysql_config文件所在机器上的目录为准)

在Python代码



conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
 改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8')
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

 

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚

cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集

cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.

import MySQLdb
try:
    conn=MySQLdb.connect(host='127.0.0.1',user='root',passwd='admin',db='mysql',port=3306)
    cur=conn.cursor()
    #cur.execute('select * from user')
    cur.execute('select version()')
    data = cur.fetchone()
    print "Databases version: %s " %  data
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])
     
import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:

    cur = conn.cursor()
    cur.execute("Create TABLE IF NOT EXISTS \
        Writers(Id INT PRIMARY KEY AUTO_INCREMENT,NAME VARCHAR(25))")
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack Luo')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Kity Alice')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Alex ok')")
import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:
    cur = conn.cursor()
    cur.execute("SELECT * from Writers")
    rows = cur.fetchall()
    for row in rows:
        print row
import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:
    cur = conn.cursor()
    cur.execute("SELECT * from Writers")
    numrows = int(cur.rowcount)
    for i in range(numrows):
        row = cur.fetchone()
        print row[0],row[1]
import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:
    cur = conn.cursor(mdb.cursors.DictCursor)
    cur.execute("SELECT * FROM Writers")

    rows = cur.fetchall()

    for row in rows:
        print "%s %s" % (row["Id"],row["NAME"])
import MySQLdb as mdb
import sys

conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:
    cur = conn.cursor()
    cur.execute("SELECT * from Writers")
    rows = cur.fetchall()
    desc = cur.description
    print 'cur.description:',desc
    print "%s %3s" % (desc[0][0],desc[1][0])
    for row in rows:
        print "%2s %3s" % row
import MySQLdb as mdb
import sys
conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
with conn:
    cur = conn.cursor()
    cur.execute("UPDATE Writers SET NAME=%s WHERE Id = %s",("Guy de Maupasant","4"))
    print "Number of rows updated: %d" % cur.rowcount
import MySQLdb as mdb
import sys
try:
    fin = open("logo.png")
    img = fin.read()
    fin.close()
except IOError,e:
    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
try:
    conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Images SET Data='%s'" % mdb.escape_string(img))
    conn.commit()
    cursor.close()
    conn.close()
except mdb.Error,e:
    print "Error %d:%s" % (e.args[0],e.args[1])
    sys.exit(1)
import MySQLdb as mdb
import sys
try:
    conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
    cursor = conn.cursor()
    cursor.execute("SELECT Data FROM Images LIMIT 1")
    fout = open('logo2.png','wb')
    fout.write(cursor.fetchone()[0])
    fout.close()
    cursor.close()
    conn.close()
except IOError,e:
    print "Error %d: %s" %(e.args[0],e.args[1])
    sys.exit(1)
import MySQLdb as mdb
import sys
try:
    conn = mdb.connect(host='127.0.0.1',user='root',passwd='admin',db='game',port=3306)
    cursor = conn.cursor()
    cursor.execte("UPDATE Writers SET Name = %s WHERE Id = %s",("JACK LUO","1"))
    cursor.execte("UPDATE Writers Set Name = %s where Id = %s ",("Alex LI",'2'))
    cursor.execte("UPDATE Writers Set Name = %s where Id = %s",("Leonid Leonov",'3'))
    conn.commit()
    cursor.close()
    conn.close()
except mdb.Error,e:
    conn.rollback()
    print "Error %d: %s" % (e.args[0],e.args[1])

    

 

你可能感兴趣的:(mysqldb)