python實現連接mysql數據庫
操作系統環境:centos7
工具:python2.7
模塊:MySQLdb
centos7 操作系統自帶的python爲2.7,只需安裝MySQLdb模塊就可以實現與mysql數據庫進行連接。
首先下載 MySQLdb 安裝包,我這邊下載的是1.2.3版本, MySQL-python-1.2.3b1.tar.gz
上傳至centos7服務器,/data 目錄下,然後進行解壓:tar -zxvf MySQL-python-1.2.3b1.tar.gz
然後進入 MySQL-python-1.2.3b1目錄,執行安裝命令: python setup.py install
安裝過程中可能會提示安裝相關的環境,根據提醒進行安裝相關的依賴即可。
以下附上代碼:
#coding=utf-8
#!/usr/bin/env python2.7
'''
Created on 2019-1-21
@author: huwj
'''
import MySQLdb
#連接mysql數據庫配置
conn = MySQLdb.connect(host='localhost',user='db_user',passwd='db_passwd',db='db_name')
cursor = conn.cursor()
def select():
#查找數據庫中的數據
sql = "select * from user limit 0,1;"
#獲取執行結果條數
n = cursor.execute(sql)
#重置遊標的位置
cursor.scroll(0,mode='absolute')
#搜取所有結果
results = cursor.fetchall()
print ("test",results)
select()
cursor.close()
conn.close()