99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀如何使用PyMySQL操作mysql數(shù)據(jù)庫
如何使用PyMySQL操作mysql數(shù)據(jù)庫
2018-01-04
收藏

如何使用PyMySQL操作mysql數(shù)據(jù)庫

在工作和生活中我們用Python處理數(shù)據(jù)的情況并不少見,而且很多情況是從數(shù)據(jù)庫取數(shù)據(jù),比如MySQL,這里我來分享下簡單的Python操作MySQL的庫pymysql。

安裝與應(yīng)用

適用環(huán)境
python版本 >=2.6或3.3
mysql版本>=4.1
安裝
可以使用pip安裝也可以手動下載安裝。
使用pip安裝,在命令行執(zhí)行如下命令:
pip install PyMySQL(大寫不行換小寫)
手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。
其中的X.X是版本(目前可以獲取的最新版本是0.7.6)。
下載后解壓壓縮包。在命令行中進(jìn)入解壓后的目錄,執(zhí)行如下的指令:
python setup.py install
建議使用pip安裝。

使用示例
連接數(shù)據(jù)庫如下:

import pymysql.cursors
config = {
'host':'127.0.0.1',
'port':3306,
'user':'root',
'password':'zhyea.com',
'db':'employees',
'charset':'utf8mb4',
'cursorclass':pymysql.cursors.DictCursor,
}

# Connect to the database
connection = pymysql.connect(**config)


插入數(shù)據(jù):
執(zhí)行sql語句前需要獲取cursor,因為配置默認(rèn)自動提交,故在執(zhí)行sql語句后需要主動commit,最后不要忘記關(guān)閉連接:

from datetime import date, datetime, timedelta
import pymysql.cursors
#連接配置信息
config = {
'host':'127.0.0.1',
'port':3306,
'user':'root',
'password':'zhyea.com',
'db':'employees',
'charset':'utf8mb4',
'cursorclass':pymysql.cursors.DictCursor,
}
# 創(chuàng)建連接
connection = pymysql.connect(**config)

# 獲取明天的時間
tomorrow = datetime.now().date() + timedelta(days=1)

# 執(zhí)行sql語句
try:
    with connection.cursor() as cursor:
# 執(zhí)行sql語句,插入記錄
    sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)'
    cursor.execute(sql, ('Robin', 'Zhyea', tomorrow, 'M', date(1989, 6, 14)));
# 沒有設(shè)置默認(rèn)自動提交,需要主動提交,以保存所執(zhí)行的語句
    connection.commit()
finally:
    connection.close();


執(zhí)行查詢:

import datetime
import pymysql.cursors
#連接配置信息
config = {
'host':'127.0.0.1',
'port':3306,
'user':'root',
'password':'zhyea.com',
'db':'employees',
'charset':'utf8mb4',
'cursorclass':pymysql.cursors.DictCursor,
}
# 創(chuàng)建連接
connection = pymysql.connect(**config)

# 獲取雇傭日期
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(2016, 12, 31)
# 執(zhí)行sql語句
try:
    with connection.cursor() as cursor:
    # 執(zhí)行sql語句,進(jìn)行查詢
    sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s'
    cursor.execute(sql, (hire_start, hire_end))
    # 獲取查詢結(jié)果
    result = cursor.fetchone()
    print(result)
    # 沒有設(shè)置默認(rèn)自動提交,需要主動提交,以保存所執(zhí)行的語句
    connection.commit()
finally:
    connection.close();

這里的查詢只取了一條查詢結(jié)果,查詢結(jié)果以字典的形式返回:

   result = cursor.fetchmany(2)


不過不建議這樣使用,最好在sql語句中設(shè)置查詢的記錄總數(shù)。獲取全部結(jié)果集可以使用fetchall方法:

result = cursor.fetchall()


因為只有兩條記錄,所以上面提到的這兩種查詢方式查到的結(jié)果是一樣的:

  [{‘last_name’: ‘Vanderkelen’, ‘hire_date’: datetime.date(2015, 8, 12), ‘first_name’: ‘Geert’}, {‘last_name’: ‘Zhyea’, ‘hire_date’: datetime.date(2015, 8, 21), ‘first_name’: ‘Robin’}]


在django中使用


在django中使用是我找這個的最初目的。目前同時支持python3.4、django1.8的數(shù)據(jù)庫backend并不好找。這個是我目前找到的最好用的。


設(shè)置DATABASES和官方推薦使用的MySQLdb的設(shè)置沒什么區(qū)別:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': 'zhyea.com',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

關(guān)鍵是這里:我們還需要在站點的__init__.py文件中添加如下的內(nèi)容:
   import pymysql
   pymysql.install_as_MySQLdb()

以上就是Python中pymysql庫的簡單使用,謝謝。


數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }