欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

linux下python3連接mysql數(shù)據(jù)庫問題

 更新時間:2015年10月18日 15:11:38   投稿:mrr  
這篇文章主要介紹了linux下python3連接mysql數(shù)據(jù)庫問題,需要的朋友可以參考下

python語言的3.x完全不向前兼容,導致我們在python2.x中可以正常使用的庫,到了python3就用不了了.比如說mysqldb

1.安裝pymysql

pymysql就是作為python3環(huán)境下mysqldb的替代物,進入命令行,使用pip安裝pymysql

pip install pymysql3

2.使用pymysql

在我們需要使用數(shù)據(jù)庫的.py文件開頭添加下面兩行

import pymysql
pymysql.install_as_MySQLdb()

第一行是引入pymysql,第二行是照顧習慣,將其當成是mysqldb一樣使用

Linux下python連接MySQL數(shù)據(jù)庫方法

要連接數(shù)據(jù)庫名稱是hhh,用戶名是tom,連接的數(shù)據(jù)表是 data_import,其中 data_import數(shù)據(jù)結構如下(5個屬性):

mysql> desc data_import; 
+---------+-------------+------+-----+---------+-------+ 
| Field   | Type        | Null | Key | Default | Extra | 
+---------+-------------+------+-----+---------+-------+ 
| id      | char(10)    | YES  |     | NULL    |       | 
| name    | char(10)    | YES  |     | NULL    |       | 
| age     | char(10)    | YES  |     | NULL    |       | 
| address | varchar(15) | YES  |     | NULL    |       | 
| hobby   | varchar(15) | YES  |     | NULL    |       | 
+---------+-------------+------+-----+---------+-------+ 
5 rows in set (0.01 sec) 

Linux下python連接MySQL數(shù)據(jù)庫完整例程:

#!/usr/bin/python 
import MySQLdb #導入庫 
conn = MySQLdb.connect(host="127.0.0.1",user="tom",passwd="123",db="hhh") 
#conn = MySQLdb.connect('localhost',"tom","123","hhh")#連接函數(shù) 
cur = conn.cursor()#獲得指向當前數(shù)據(jù)庫的指針 
#cur.execute('show tables;') 
cur.execute("select * from data_import;")#用execute()方法執(zhí)行SQL語句 
result = cur.fetchall()#用fetchall()方法得到行信息 
for record in result: 
    print  "%s \t%s \t%s \t%s \t%s " % record#格式化輸出 
 
cur.close()#關閉指針對象 
conn.close()#關閉數(shù)據(jù)庫連接對象 

運行結果(部分):

[root@localhost python]# ./python_mysql.py 
1       TOM     24      Beijing         football 
2       LIU     27      heibei  football 
3       JIM     26      shandong        football 
4       HAN     28      beijing         football 
5       MENG    25      beijing         tennis 
1       TOM     24      Beijing         football 

好了,本文全部內容介紹完畢,希望本文分享對大家有所幫助。

相關文章

最新評論