[Python]Python操作/管理Mysql学习(一)

先确定环境是否已支持MySQLdb模块,如果没有,请安装,如下:
[root@bw-vm-soft ~]# wget http://jaist.dl.sourceforge.net/project/mysql-python/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
[root@bw-vm-soft ~]# tar zxvf MySQL-python-1.2.3.tar.gz
[root@bw-vm-soft ~]# cd MySQL-python-1.2.3

修改site.cfg中的mysql_config路径
vi site.cfg 
mysql_config = /usr/local/webserver/mysql/bin/mysql_config   (根据mysql安装路径而定)

[root@bw-vm-soft MySQL-python-1.2.3]# python setup.py build
[root@bw-vm-soft MySQL-python-1.2.3]# python setup.py install
确认安装成功后

请在/etc/ld.so.conf添加/usr/local/webserver/mysql/lib/mysql,然后执行 ldconfig

之后就可以进入正题,操作/管理Mysql了

例1、插入数据
###########################################################################
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import MySQLdb as mdb
import sys

con = mdb.connect('localhost','root','123123','pythontest')
with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS \
        Users(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
    cur.execute("INSERT INTO Users(Name) VALUES('Richard shen')")
    cur.execute("INSERT INTO Users(Name) VALUES('Zhang san')")
    cur.execute("INSERT INTO Users(Name) VALUES('Li si')")
    cur.execute("INSERT INTO Users(Name) VALUES('Wang dongdong ')")
###########################################################################

例2、查看数据

#!/usr/bin/env python
#_*_coding:UTF-8 _*_
import MySQLdb as mdb
import sys

con = mdb.connect('localhost','root','123123','pythontest')

with con:
    cur = con.cursor()
    cur.execute("SELECT * FROM Users")
 
    numrows = int(cur.rowcount)
    for i in range(numrows):
        row = cur.fetchone()
        print row[0],row[1]
  
执行结果:
1 Richard shen
2 Zhang san
3 Li si
4 Wang dongdong

这是数据库最基本的操作,以后学习中会继续介绍相关内容~~若有好建议/问题,请联系~QQ群:24967504

你可能感兴趣的:(mysql,python,mysqldb)