linux下python3串連mysql資料庫問題_linux shell

來源:互聯網
上載者:User

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

1.安裝pymysql

pymysql就是作為python3環境下mysqldb的替代物,進入命令列,使用pip安裝pymysql

pip install pymysql3

2.使用pymysql

在我們需要使用資料庫的.py檔案開頭添加下面兩行

import pymysql
pymysql.install_as_MySQLdb()

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

Linux下python串連MySQL資料庫方法

要串連資料庫名稱是hhh,使用者名稱是tom,串連的資料表是 data_import,其中 data_import資料結構如下(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資料庫完整常式:

#!/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")#串連函數 cur = conn.cursor()#獲得指向當前資料庫的指標 #cur.execute('show tables;') cur.execute("select * from data_import;")#用execute()方法執行SQL語句 result = cur.fetchall()#用fetchall()方法得到行資訊 for record in result:     print  "%s \t%s \t%s \t%s \t%s " % record#格式化輸出  cur.close()#關閉指標對象 conn.close()#關閉資料庫連接對象 

運行結果(部分):

[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 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.