轉載 Python 操做 MySQL 的正確姿式 - 琉璃塊

<div class="post"> <h1 class="postTitle"> <a id="cb_post_title_url" class="postTitle2" href="https://www.cnblogs.com/liuliliuli2017/p/6763988.html">Python 操做 MySQL 的正確姿式</a> </h1> <div class="clear"></div> <div class="postBody"> <div id="cnblogs_post_body" class="blogpost-body cnblogs-markdown"><p>收錄待用,修改轉載已取得<a href="https://www.qcloud.com/">騰訊雲</a>受權</p> <hr> <p>做者 |邵建永<br> 編輯 | 顧鄉</p> <p>使用Python進行MySQL的庫主要有三個,Python-MySQL(更熟悉的名字多是MySQLdb),PyMySQL和SQLAlchemy。</p> <p>Python-MySQL資格最老,核心由C語言打造,接口精煉,性能最棒,缺點是環境依賴較多,安裝複雜,近兩年已中止更新,只支持Python2,不支持Python3。</p> <p>PyMySQL爲替代Python-MySQL而生,純python打造,接口與Python-MySQL兼容,安裝方便,支持Python3。</p> <p>SQLAlchemy是一個ORM框架,它並不提供底層的數據庫操做,而是要藉助於MySQLdb、PyMySQL等第三方庫來完成,目前SQLAlchemy在Web編程領域應用普遍。</p> <p>本文主要介紹PyMySQL的正確使用方法,示例代碼都是選自實戰項目。</p> <h2 id="安裝">安裝</h2> <p>簡單的方式:</p> <pre><code class="hljs cmake">pip <span class="hljs-keyword">install</span> pymysql </code></pre> <p>若是沒法聯網,須要進行離線安裝,例如:</p> <pre><code class="hljs css"><span class="hljs-selector-tag">pip</span> <span class="hljs-selector-tag">install</span> <span class="hljs-selector-tag">pymysql-x</span><span class="hljs-selector-class">.x</span><span class="hljs-selector-class">.x</span><span class="hljs-selector-class">.tar</span><span class="hljs-selector-class">.gz</span> </code></pre> <h2 id="導入">導入</h2> <pre><code class="hljs haskell"><span class="hljs-keyword">import</span> pymysql </code></pre> <h2 id="鏈接">鏈接</h2> <pre><code class="hljs ruby"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect_wxremit_db</span><span class="hljs-params">()</span></span>: <span class="hljs-keyword">return</span> pymysql.connect(host=<span class="hljs-string">'10.123.5.28'</span>, port=<span class="hljs-number">3306</span>, user=<span class="hljs-string">'root'</span>, password=<span class="hljs-string">'root1234'</span>, database=<span class="hljs-string">'db_name'</span>, charset=<span class="hljs-string">'latin1'</span>) </code></pre> <h2 id="查詢">查詢</h2> <pre><code class="hljs lua">def query_country_name(cc2): sql_str = (<span class="hljs-string">"SELECT Fcountry_name_zh"</span> + <span class="hljs-string">" FROM t_country_code"</span> + <span class="hljs-string">" WHERE Fcountry_2code='%s'"</span> % (cc2)) logging.info(sql_str)javascript

con = mysql_api.connect_wxremit_db()
cur = con.cursor()
cur.<span class="hljs-built_in">execute</span>(sql_str)
rows = cur.fetchall()
cur.<span class="hljs-built_in">close</span>()
con.<span class="hljs-built_in">close</span>()

<span class="hljs-built_in">assert</span> <span class="hljs-built_in">len</span>(rows) == <span class="hljs-number">1</span>, <span class="hljs-string">'Fatal error: country_code does not exists!'</span>
<span class="hljs-keyword">return</span> rows[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]

</code></pre>css

<h2 id="簡單插入">簡單插入</h2> <pre><code class="hljs python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">insert_file_rec</span><span class="hljs-params">(self, file_name, file_md5)</span>:</span> con = mysql_api.connect_wxremit_db() cur = con.cursor() <span class="hljs-keyword">try</span>: sql_str = (<span class="hljs-string">"INSERT INTO t_forward_file (Ffile_name, Ffile_md5)"</span>, + <span class="hljs-string">" VALUES ('%s', '%s')"</span> % (file_name, file_md5)) cur.execute(sql_str) con.commit() <span class="hljs-keyword">except</span>: con.rollback() logging.exception(<span class="hljs-string">'Insert operation error'</span>) <span class="hljs-keyword">raise</span> <span class="hljs-keyword">finally</span>: cur.close() con.close() </code></pre> <h2 id="批量插入">批量插入</h2> <pre><code class="hljs python">remit_ids = [(<span class="hljs-string">'1234'</span>, <span class="hljs-string">'CAD'</span>), (<span class="hljs-string">'5678'</span>, <span class="hljs-string">'HKD'</span>)]html

con = mysql_api.connect_wxremit_db() cur = con.cursor() <span class="hljs-keyword">try</span>: cur.executemany(<span class="hljs-string">"INSERT INTO t_order (Fremit_id, Fcur_type, Fcreate_time"</span> + <span class="hljs-string">" VALUES (%s, %s, now())"</span>, new_items) <span class="hljs-keyword">assert</span> cur.rowcount == len(remit_ids), <span class="hljs-string">'my error message'</span> con.commit() <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e: con.rollback() logging.exception(<span class="hljs-string">'Insert operation error'</span>) <span class="hljs-keyword">finally</span>: cur.close() con.close() </code></pre>java

<h2 id="更新">更新</h2> <pre><code class="hljs python"> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_refund_trans</span><span class="hljs-params">(self, remit_id)</span>:</span> con = mysql_api.connect_wxremit_db() cur = con.cursor() <span class="hljs-keyword">try</span>: sql_str = (<span class="hljs-string">"SELECT Fremit_id"</span> + <span class="hljs-string">" FROM t_wxrefund_trans"</span> + <span class="hljs-string">" WHERE Fremit_id='%s'"</span> % remit_id + <span class="hljs-string">" FOR UPDATE"</span>) logging.info(sql_str)python

cur.execute(sql_str)
        <span class="hljs-keyword">assert</span> cur.rowcount == <span class="hljs-number">1</span>, <span class="hljs-string">'Fatal error: The wx-refund record be deleted!'</span>

        sql_str = (<span class="hljs-string">"UPDATE t_wxrefund_trans"</span>
                    + <span class="hljs-string">" SET Fcheck_amount_flag=1"</span>
                    + <span class="hljs-string">", Fmodify_time=now()"</span>
                    + <span class="hljs-string">" WHERE Fremit_id='%s'"</span> % remit_id
        logging.info(sql_str)
        cur.execute(sql_str)

        <span class="hljs-keyword">assert</span> cur.rowcount == <span class="hljs-number">1</span>, <span class="hljs-string">'The number of affected rows not equal to 1'</span>
        con.commit()
    <span class="hljs-keyword">except</span>:
        con.rollback()
        logging.exception(<span class="hljs-string">'Update operation error'</span>)
        <span class="hljs-keyword">raise</span>
    <span class="hljs-keyword">finally</span>:
        cur.close()
        con.close()

</code></pre>mysql

<p>PyMySQL已經至關成熟,和Python-MySQL同樣,它在不少Linux發行版本中都是可選的安裝組件。</p> <hr> <p>原文連接:<a href="https://www.qcloud.com/community/article/687813" class="uri">https://www.qcloud.com/community/article/687813</a></p> </div><div id="MySignature"></div> <div class="clear"></div> <div id="blog_post_info_block"> <div id="BlogPostCategory"></div> <div id="EntryTag"></div> <div id="blog_post_info"><div id="green_channel"> <a href="javascript:void(0);" id="green_channel_digg" onclick="DiggIt(6763988,cb_blogId,1);green_channel_success(this,'謝謝推薦!');">好文要頂</a> <a id="green_channel_follow" onclick="follow('0657e7f7-6520-e711-9fc1-ac853d9f53cc');" href="javascript:void(0);">關注我</a> <a id="green_channel_favorite" onclick="AddToWz(cb_entryId);return false;" href="javascript:void(0);">收藏該文</a> <a id="green_channel_weibo" href="javascript:void(0);" title="分享至新浪微博" onclick="ShareToTsina()"><img src="//common.cnblogs.com/images/icon_weibo_24.png" alt=""></a> <a id="green_channel_wechat" href="javascript:void(0);" title="分享至微信" onclick="shareOnWechat()"><img src="//common.cnblogs.com/images/wechat.png" alt=""></a> </div> <div id="author_profile"> <div id="author_profile_info" class="author_profile_info"> <a href="http://home.cnblogs.com/u/liuliliuli2017/" target="_blank"><img src="//pic.cnblogs.com/face/sample_face.gif" class="author_avatar" alt=""></a> <div id="author_profile_detail" class="author_profile_info"> <a href="http://home.cnblogs.com/u/liuliliuli2017/">琉璃塊</a><br> <a href="http://home.cnblogs.com/u/liuliliuli2017/followees">關注 - 0</a><br> <a href="http://home.cnblogs.com/u/liuliliuli2017/followers">粉絲 - 0</a> </div> </div> <div class="clear"></div> <div id="author_profile_honor"></div> <div id="author_profile_follow"> <a href="javascript:void(0);" onclick="follow('0657e7f7-6520-e711-9fc1-ac853d9f53cc');return false;">+加關注</a> </div> </div> <div id="div_digg"> <div class="diggit" onclick="votePost(6763988,'Digg')"> <span class="diggnum" id="digg_count">0</span> </div> <div class="buryit" onclick="votePost(6763988,'Bury')"> <span class="burynum" id="bury_count">0</span> </div> <div class="clear"></div> <div class="diggword" id="digg_tips"> </div> </div> <script type="text/javascript"> currentDiggType = 0; </script></div> <div class="clear"></div> <div id="post_next_prev"><a href="https://www.cnblogs.com/liuliliuli2017/p/6763963.html" class="p_n_p_prefix">« </a> 上一篇:<a href="https://www.cnblogs.com/liuliliuli2017/p/6763963.html" title="發佈於2017-04-25 20:58">程序員的江湖:從黑木崖到回龍觀</a><br><a href="https://www.cnblogs.com/liuliliuli2017/p/6782675.html" class="p_n_p_prefix">» </a> 下一篇:<a href="https://www.cnblogs.com/liuliliuli2017/p/6782675.html" title="發佈於2017-04-28 17:47">Nginx + Lua搭建文件上傳下載服務</a><br></div> </div>git

</div>
	<div class="postDesc">posted @ <span id="post-date">2017-04-25 21:26</span> <a href="https://www.cnblogs.com/liuliliuli2017/">琉璃塊</a> 閱讀(<span id="post_view_count">12782</span>) 評論(<span id="post_comment_count">0</span>)  <a href="https://i.cnblogs.com/EditPosts.aspx?postid=6763988" rel="nofollow">編輯</a> <a href="#" onclick="AddToWz(6763988);return false;">收藏</a></div>
</div>
相關文章
相關標籤/搜索