Windows下安裝MySQL-python
下載地址:https://pypi.python.org/pypi/MySQL-python/1.2.5 安裝到系統(tǒng)即可。
linux下安裝MySQL-python以連接MySQL:
下載地址:https://pypi.python.org/pypi/MySQL-python/
解壓后,進(jìn)入目錄下,執(zhí)行python setup.py install
安裝過程中,常會(huì)遇到的問題:
1、 提示找不到mysql_config的話,一般是由于mysql采用的是lnmp一鍵安裝包安裝的,路徑
解決:locate mysql_config找到mysql_config這個(gè)文件的位置,然后ln -s做個(gè)軟連接到/usr/bin/下。
2、 Ubuntu下提示缺少'x86_64-linux-gnu-gcc'時(shí),需要安裝python-dev包:
解決:sudo apt-get install python-dev -y
3、 CentOS下提示command 'gcc' failed with exit status 1
解決:yum install gcc python-devel -y
安裝完成后,進(jìn)入python,執(zhí)行import MySQLdb看導(dǎo)入是否能成功。
補(bǔ)充:
我在ubuntu下操作時(shí)候,發(fā)現(xiàn)無法連接數(shù)據(jù)庫,ss -lnt發(fā)現(xiàn)mysql只監(jiān)聽在回環(huán)地址上的3306端口,需要修改下。
修改Ubuntu的mysql,將其監(jiān)聽端口127.0.0.1:3306改為允許外部連接的方法:
編輯/etc/mysql/my.cnf(可能配置參數(shù)再此目錄下的其它文件中,仔細(xì)找找)
修改bind-address = 0.0.0.0 表示允許任意IP訪問。
然后執(zhí)行 /etc/init.d/mysql restart重啟mysqlserver服務(wù)即可
# 下面是一個(gè)Python操作數(shù)據(jù)庫的例子:
#!/usr/bin/env python# -*- coding:utf8 -*-import MySQLdbconn = MySQLdb.connect(host = '192.168.2.14',port = 3306,user = 'root',passwd = '123456',db = 'demo',)# 操作數(shù)據(jù)庫首先需要?jiǎng)?chuàng)建游標(biāo)cur = conn.cursor()# 通過游標(biāo)cur操作execute()方法可以寫入純sql語句,如下:# 創(chuàng)建數(shù)據(jù)表# cur.execute("create table teacher (id int(5),name varchar(20),class varchar(20),age varchar(10))")# 插入數(shù)據(jù)# cur.execute("insert into teacher values(23,'zhangsan','science',15)")# 修改數(shù)據(jù)# cur.execute("update teacher set id=100 where name='zhangsan'")# 刪除數(shù)據(jù)# cur.execute("delete from teacher where id=100")#插入一條數(shù)據(jù)【也可以用像下面這種寫法】sqli="insert into teacher values(%s,%s,%s,%s)"cur.execute(sqli, (23,'zhangsan','science',15))# 使用executemany一次性向數(shù)據(jù)表中插入多條值,返回值為受影響的行數(shù)。sqli="insert into teacher values(%s,%s,%s,%s)"cur.executemany(sqli,[(11,'wangwu','art',23),(8,'john','math',22),(3,'Tom','physical',25),])# 最后關(guān)閉游標(biāo),執(zhí)行提交操作,并關(guān)閉數(shù)據(jù)庫連接cur.close()conn.commit()conn.close()檢索并輸出數(shù)據(jù)
#!/usr/bin/env python# -*- coding:utf8 -*-import MySQLdbconn = MySQLdb.connect(host = '192.168.2.14',port = 3306,user = 'root',passwd = '123456',db = 'demo',)cur = conn.cursor()# 獲得表中有多少條數(shù)據(jù)aa = cur.execute("select * from teacher")cur.fetchone() # fetchone()方法可以幫我們獲得表中的數(shù)據(jù),但是每執(zhí)行一次輸出一行滿足條件的值cur.fetchone()......cur.scroll(0,'absolute')# 這樣能將游標(biāo)定位到表中的第一條數(shù)據(jù)info = cur.fetchmany(aa)for i in info:print icur.close()conn.commit()conn.close()有關(guān)Python對(duì)數(shù)據(jù)庫操作小編就給大家介紹這么多,希望對(duì)大家有所幫助!
新聞熱點(diǎn)
疑難解答
圖片精選