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

熱線電話:13121318867

登錄
首頁精彩閱讀Python也能操作Mysql數(shù)據(jù)庫
Python也能操作Mysql數(shù)據(jù)庫
2021-08-02
收藏

來源:Python爬蟲與數(shù)據(jù)挖掘

作者: Python進階者

大家好,我是Python進階者。

前言

我們在進行Python編程的時候,時常要將一些數(shù)據(jù)保存起來,其中最方便的莫過于保存在文本文件了。但是如果保存的文件太大,用文本文件就不太現(xiàn)實了,畢竟打開都是個問題,這個時候我們需要用到數(shù)據(jù)庫。提到數(shù)據(jù)庫,相信大部分人都不會陌生,今天我們要學(xué)的就是數(shù)據(jù)庫中小編自認為最棒的Mysql數(shù)據(jù)庫了。

一、下載導(dǎo)入模塊

為了讓Python與Mysql 交互,這里我們需要用到Pymsql模塊才行。

下載模塊:

pip install pymysql

導(dǎo)入模塊:

import pymysql

二、創(chuàng)建數(shù)據(jù)庫

打開數(shù)據(jù)庫連接軟件 SqlYong,如圖:

Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

輸入命令:

CREATE DATABASE IF NOT EXISTS people;

這樣就創(chuàng)建了一個people 數(shù)據(jù)庫。

三、創(chuàng)建數(shù)據(jù)表,并寫入數(shù)據(jù)

USE people; CREATE TABLE IF NOT EXISTS student(id INT PRIMARY KEY AUTO_INCREMENT,NAME CHAR(10) UNIQUE,score INT NOT NULL,tim DATETIME)ENGINE=INNOBASE CHARSET utf8; INSERT INTO student(NAME,score,tim)VALUES('fasd',60,'2020-06-01') SELECT * FROM student;

通過上述操作便創(chuàng)建了一個數(shù)據(jù)表Student并向其中寫入了數(shù)據(jù),結(jié)果如下:

Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

我們可以一行代碼刪除這個插入的 數(shù)據(jù):

TRUNCATE student;

四、Mysql與Python建立連接

將下圖中的參數(shù)依次填入初始化參數(shù)中,

Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')

這樣就連接到了people數(shù)據(jù)庫,可以看下連接成功的打印信息:

Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

可以看到我們打印了Mysql的版本和Host信息。

五、創(chuàng)建游標執(zhí)行操作

1.創(chuàng)建游標

cur=db.cursor

2.編寫插入數(shù)據(jù)表達式

sql="INSERT INTO student(NAME,score,tim)VALUES('任性的90后boy',100,now())"

3.開啟游標事件

cur.begin()

4.執(zhí)行數(shù)據(jù)庫語句,異常判斷

try:
    cur.execute(sql) 執(zhí)行數(shù)據(jù)庫語句
except Exception as e: print(e)
    db.rollback()   發(fā)生異常進行游標回滾操作 else:
    db.commit()   提交數(shù)據(jù)庫操作 finally:
    cur.close()  關(guān)閉游標
    db.close()  關(guān)閉數(shù)據(jù)庫

5,執(zhí)行插入操作

數(shù)據(jù)庫建立好后,我們可以對它們進行插入數(shù)據(jù)的操作。

import time
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="INSERT INTO student(NAME,score,tim) VALUES ('%s',%d,'%s')" data=('HW',90,tt) try:
  cur.execute(sql%data)
except Exception as e:
  print(e)
  db.rollback() else:
  db.commit() finally:
  cur.close()
  db.close()
Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

這樣就可以將數(shù)據(jù)插入進去了。我們還可以自定義插入:

import pymysql
import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
s=input('string:')
d=input('number:')
sql="INSERT INTO student(NAME,score,tim)VALUES('%s','%s','%s')" try:
  data=(s,d,tt)
  cur.execute(sql%data)
except Exception as e: print(e)
  db.rollback() else:
  db.commit()
finally:
  cur.close()
  db.close()
Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

另外,我們也可以同時插入多條數(shù)據(jù),只需先定義好所有的數(shù)據(jù),然后在調(diào)用即可,這里需要用到插入多條數(shù)據(jù)的函數(shù)Executemany,在這里我插入十萬條數(shù)據(jù),并測試插入時間,步驟如下:

import pymysql
import time start=time.time()
tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin() sql="insert into student(NAME,score,tim)values(%s,%s,%s)" def get():
  ab=[] for y in range(1,100000): if y>=100: data=('user-'+str(y),str(str(float('%.f'%(y%100)))),tt) else: data=('user-'+str(y),str(y),tt)
    ab.append(data) return ab


try: data=get()
  cur.executemany(sql,data) except Exception as e:
  print(e)
  db.rollback() else:
  db.commit()
finally:
  print('插入數(shù)據(jù)完畢')
  cur.close()
  db.close() end=time.time()
  print('用時:',str(end-start))

6.執(zhí)行更新操作

有些數(shù)據(jù)我們覺得它過時了,想更改,就要更新它的數(shù)據(jù)。

import time
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="update student set name='zjj' where score=100 " 當分數(shù)是100分的時候?qū)⒚指臑閦jj try:
  cur.execute(sql%data) except Exception as e:
  print(e)
  db.rollback() else:
  db.commit() finally:
  cur.close()
  db.close()
Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

7.執(zhí)行刪除操作

有時候一些數(shù)據(jù)如果對于我們來說沒有任何作用了的話了,我們就可以將它刪除了,不過這里是刪除數(shù)據(jù)表中的一條記錄。

import pymysql
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="delete from student where name='fasd';" 當名字等于‘fasd’的時候刪除這個記錄 try:
  cur.execute(sql) except Exception as e:
  print(e)
  db.rollback() else:
  db.commit() finally:
  cur.close()
  db.close()
Python也能操作My<a href='/map/sqlshujuku/' style='color:#000;font-size:inherit;'>sql數(shù)據(jù)庫</a>

你也可以刪除表中所有的數(shù)據(jù),只需將Sql語句改為:

sql='TRUNCATE student;'

當然你也可以刪除表,但是一般不建議這樣做,以免誤刪:

DROP TABLE IF EXISTS student;

8.執(zhí)行查詢操作

有時候我們需要對數(shù)據(jù)庫中的數(shù)據(jù)進行查詢,Python也能輕松幫我們搞定。

import pymysql
import time tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="select * from student;" try:
  cur.execute(sql)
  res=cur.fetchall() 查詢數(shù)據(jù)庫中的數(shù)據(jù) for y in res: print(y) 打印數(shù)據(jù)庫中標的所有數(shù)據(jù),以元祖的形式
except Exception as e: print(e)
  db.rollback() else:
  db.commit()
finally:
  cur.close()
  db.close()

六、總結(jié)

在我們進行網(wǎng)絡(luò)爬蟲的時候,需要保存大量數(shù)據(jù),這個時候數(shù)據(jù)庫就派上用場了,可以更方便而且更快捷保存數(shù)據(jù)。

數(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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(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ù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 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); }