封裝的python mysql操作ORM類


這段時間寫項目用了python的mysql模塊,覺得sqlalchemy太龐大就自己封裝了一個簡單的基於mysql-python的ORM文件。功能目前剛好夠用以后會慢慢完善。這個操作類中解決了python編碼和入mysql庫編碼不統一的問題,同時還解決了mysql的反斜杠'\'會被轉義丟棄的問題。

1、安裝mysql-python模塊

python的mysql操作需要安裝mysql-python庫,安裝方法如下。

sudo pip install MySQL-python

如果安裝的時候報錯,提示EnvironmentError: mysql_config not found,請安裝libmysqld-dev

2、我的mysql-python封裝操作模型

首先是mysql連接配置文件config.py:

#Mysql配置
mysql_host='localhost'
mysql_user='root'
mysql_passwd='12345'
mysql_db='test'
mysql_charset='utf8'

然后是封裝的操作類,由於代碼比較長,請移步github查看。下面我說下簡單的用法:

#!/usr/bin/python
#-*- coding:utf-8 -*-
#在config.py里配置數據庫連接
from mysql_conn import myMdb

mydb = myMdb()

#新建表結構
mydb.setTable('testtablename',
            "(`test_id` int(10) NOT NULL AUTO_INCREMENT,`test_col1` varchar(255) NOT NULL,`test_col2` varchar(255) NOT NULL, PRIMARY KEY (`test_id`), KEY `test_col1` (`test_col1`), KEY `test_col2` (`test_col2`)) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;"
            )

#新增數據記錄
tag = mydb._insert({'test_col1':'123','test_col2':'455'})._from('testtablename').execute()
print tag

#修改數據記錄
tag = mydb._update({'test_col2':'456'})._from('testtablename')._where({'column':'test_id','data':'1','relation':'='}).execute()
print tag

#刪除數據記錄
tag = mydb._delete()._from('testtablename')._where({'column':'test_id','data':'3','relation':'<'}).execute()
print tag

#查詢前100條數據並排序
rs = mydb._select('*')._from('testtablename')._where({'column':'test_col1','data':'123','relation':'='})._where({'column':'test_col2','data':'456','relation':'!='})._limit(100,1)._order({'test_id':'DESC'}).execute()
print rs

#兩表聯合查詢
rs = mydb._select('a.*')._from('testtablename_1','a')._leftjoin('testtablename_2','b','a.test_col1=b.test_col1')._where({'column':'a.test_col1','data':'123','relation':'='}).execute()
print rs

#支持上下文管理方式調用
with myMdb() as mydb:
    tag = mydb._insert({'test_col1':'123','test_col2':'455'})._from('testtablename').execute()
print tag

#打印調試最近一次執行的sql語句
print mydb.getsql

 

如果使用mysql-python官方擴展的時候報錯

OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")

其原因是我將mysql的sock文件已經調整到/tmp/mysql.sock,所以必須在mysqldb中指定sock的路徑,unix_socket參數指定了sock文件的路徑

mdb.connect(host=config.mysql_host, user=config.mysql_user, passwd=config.mysql_passwd, db=config.mysql_db, charset=config.mysql_charset, unix_socket='/tmp/mysql.sock')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM