python与mysql数据库连接衍生的几个问题

python与mysql数据库连接衍生的几个问题

mysql_config not found问题

在进行python-mysql装载时mysql_config not found这个错误出现,要如何解决?

  • 出现这种错误的时候,要分析一下,如果是常规的装载,则也许是缺少几个组件,此时只需要加载上去即可
    • sudo updatedb
    • locate mysql config
    • mysql_config的位置为:/usr/bin/mysql_config在mysql-python源码包下找到:setup_posix.py 文件,然后找到文件中的mysql_config.path 将其值改为:/usr/bin/mysql_config,然后 sudo python setup.py install ,就可以了
  • 如果是lnmp一键装载的,则只需要一条命令就可以解决:
    • ln -s /usr/local/mysql/bin/mysql_config /usr/local/bin/mysql_config
    • 此命令是将在/usr/local/mysql/bin/里面的文件连接到了/usr/local/bin目录下
    • 此时再次运行pip install python-mysql就不会再报错了。

python数据库连接代码示例


#coding=utf-8
import MySQLdb
con = MySQLdb.connect('localhost','root','mima','shujubiao',charset="utf-8")
with con:
    cur = con.cursor()
    cur.execute("select `*` from shujubiao limit 5")
    numrows = int(cur.rowcount)
    for i in range(numrows):
        row = cur.fetchone()
        print row

创建一个表并且插入数据

import MySQLdb as mdb
import sys

con = mdb.connect('localhost','root','mima','Writes');

with con:

    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS \
                Writes(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")

    cur.execute("INSERT INTO Writes(Name) VALUES('jack london')")
    cur.execute("INSERT INTO Writes(Name) VALUES('honore de balzac')")
    cur.execute("INSERT INTO Writes(Name) VALUES('lion feuchtwanger')")
    cur.execute("INSERT INTO Writes(Name) VALUES('emile zola')")
    cur.execute("INSERT INTO Writes(Name) VALUES('truman capote')")

ckhero

发表评论

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax