先肯定環境是否已支持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.3python
修改site.cfg中的mysql_config路徑
vi site.cfg
mysql_config = /usr/local/webserver/mysql/bin/mysql_config (根據mysql安裝路徑而定)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
確認安裝成功後web
請在/etc/ld.so.conf添加/usr/local/webserver/mysql/lib/mysql,而後執行 ldconfigsql
以後就能夠進入正題,操做/管理Mysql了數據庫
例一、插入數據
###########################################################################
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import MySQLdb as mdb
import syside
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 ')")
###########################################################################學習
例二、查看數據fetch
#!/usr/bin/env python
#_*_coding:UTF-8 _*_
import MySQLdb as mdb
import sysui
con = mdb.connect('localhost','root','123123','pythontest').net
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