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

熱線電話:13121318867

登錄
首頁(yè)精彩閱讀Python連接MySQL數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)
Python連接MySQL數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)
2019-08-29
收藏
Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

作者 | CDA數(shù)據(jù)分析師

來(lái)源 | CDA數(shù)據(jù)分析研究院

本文涉及到的開(kāi)發(fā)環(huán)境:

  • 操作系統(tǒng) Windows 10
  • 數(shù)據(jù)庫(kù) MySQL 8.0
  • Python 3.7.2
  • pip 19.0.3

兩種方法進(jìn)行數(shù)據(jù)庫(kù)的連接分別是PyMySQLmysql.connector

步驟

  1. 連接數(shù)據(jù)庫(kù)
  2. 生成游標(biāo)對(duì)象
  3. 執(zhí)行SQL語(yǔ)句
  4. 關(guān)閉游標(biāo)
  5. 關(guān)閉連接

PyMySQL

PyMySQL : 是封裝了MySQL驅(qū)動(dòng)的Python驅(qū)動(dòng),一個(gè)能使Python連接到MySQL的庫(kù)

環(huán)境要求:Python version >= 3.4

PyMySQL安裝

安裝

Win鍵+X鍵再按I鍵,調(diào)出Windows PowerShell窗口,輸入

pip install PyMySQL

回車(chē)

運(yùn)行結(jié)果如下則安裝成功

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

pip version ===19.0.3

查看版本

查看PyMySQL的版本,輸入

pip show PyMySQL

回車(chē)

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

利用PyMySQL連接數(shù)據(jù)庫(kù)

首先我們的MySQL數(shù)據(jù)庫(kù)已安裝,且已建好名為test的數(shù)據(jù)庫(kù),其中有名為student的表

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

import pymysql

#連接數(shù)據(jù)庫(kù)

conn=pymysql.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

sql="select * from `student` " # SQL語(yǔ)句

cur.execute(sql) # 執(zhí)行SQL語(yǔ)句

data = cur.fetchall() # 通過(guò)fetchall方法獲得數(shù)據(jù)

for i in data[:2]: # 打印輸出前2條數(shù)據(jù)

print (i)

cur.close() # 關(guān)閉游標(biāo)

conn.close() # 關(guān)閉連接

上述代碼中,實(shí)現(xiàn)了通過(guò)Python連接MySQL查詢所有的數(shù)據(jù),并輸出前2條數(shù)據(jù)的功能。執(zhí)行結(jié)果如下:

('a', '趙大', '16')

('b', '錢(qián)二', '16')

mysql.connector

mysql-connector-python:是MySQL官方的純Python驅(qū)動(dòng);

mysql.connector安裝

安裝

pip install mysql

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

查看版本

pip show mysql

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

利用 mysql.connector連接數(shù)據(jù)庫(kù)

首先我們的MySQL數(shù)據(jù)庫(kù)已安裝,且已建好名為test的數(shù)據(jù)庫(kù),其中有名為student的表

Python連接My<a href='/map/sql/' style='color:#000;font-size:inherit;'>SQL</a>數(shù)據(jù)庫(kù)方法介紹(超詳細(xì)!手把手項(xiàng)目案例操作)

import mysql.connector

conn=mysql.connector.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

sql="select * from `student` " # SQL語(yǔ)句

cur.execute(sql) # 執(zhí)行SQL語(yǔ)句

data = cur.fetchall() # 通過(guò)fetchall方法獲得數(shù)據(jù)

for i in data[:2]: # 打印輸出前2條數(shù)據(jù)

print (i)

cur.close() # 關(guān)閉游標(biāo)

conn.close() # 關(guān)閉連接

上述代碼中,實(shí)現(xiàn)了通過(guò)Python連接MySQL查詢所有的數(shù)據(jù),并輸出前2條數(shù)據(jù)的功能。執(zhí)行結(jié)果如下:

('a', '趙大', '16')

('b', '錢(qián)二', '16')

Python對(duì)MySql數(shù)據(jù)庫(kù)實(shí)現(xiàn)增刪改查

接下來(lái)我們以用pymysql包為例,介紹一下如何用Python對(duì)數(shù)據(jù)庫(kù)中的數(shù)據(jù)進(jìn)行增刪改查 。

import pymysql

#連接數(shù)據(jù)庫(kù)

conn=pymysql.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

#=============插入語(yǔ)句===============================

sql= "INSERT INTO student VALUES ('p','魏六','17')"

#===================================================

try:

cur.execute(sql1) # 執(zhí)行插入的sql語(yǔ)句

conn.commit() # 提交到數(shù)據(jù)庫(kù)執(zhí)行

except:

coon.rollback()# 如果發(fā)生錯(cuò)誤則回滾

conn.close() # 關(guān)閉數(shù)據(jù)庫(kù)連接

然后我們?cè)龠\(yùn)行查詢語(yǔ)句

import mysql.connector

conn=mysql.connector.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

sql="select * from `student` " # SQL語(yǔ)句

cur.execute(sql) # 執(zhí)行SQL語(yǔ)句

data = cur.fetchall() # 通過(guò)fetchall方法獲得數(shù)據(jù)

for i in data[:]: # 打印輸出所有數(shù)據(jù)

print (i)

cur.close() # 關(guān)閉游標(biāo)

conn.close() # 關(guān)閉連接

執(zhí)行結(jié)果就是

('b', '錢(qián)二', '16')

('c', '張三', '17')

('d', '李四', '17')

('e', '王五', '16')

('a', '趙大', '16')

('p', '魏六', '17')

import pymysql

#連接數(shù)據(jù)庫(kù)

conn=pymysql.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

#=============刪除語(yǔ)句===============================

sql = "DELETE FROM student WHERE `學(xué)號(hào)` = "a"

#===================================================

try:

cur.execute(sql) # 執(zhí)行插入的sql語(yǔ)句

conn.commit() # 提交到數(shù)據(jù)庫(kù)執(zhí)行

except:

coon.rollback()# 如果發(fā)生錯(cuò)誤則回滾

conn.close() # 關(guān)閉數(shù)據(jù)庫(kù)連接

import pymysql

#連接數(shù)據(jù)庫(kù)

conn=pymysql.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

#=============刪除語(yǔ)句===============================

sql ="UPDATE student SET `學(xué)員姓名` = '歐陽(yáng)' WHERE `學(xué)號(hào)` = 'b' "

#===================================================

try:

cur.execute(sql) # 執(zhí)行插入的sql語(yǔ)句

conn.commit() # 提交到數(shù)據(jù)庫(kù)執(zhí)行

except:

coon.rollback()# 如果發(fā)生錯(cuò)誤則回滾

conn.close() # 關(guān)閉數(shù)據(jù)庫(kù)連接

import pymysql

#連接數(shù)據(jù)庫(kù)

conn=pymysql.connect(host = '127.0.0.1' # 連接名稱,默認(rèn)127.0.0.1

,user = 'root' # 用戶名

,passwd='password' # 密碼

,port= 3306 # 端口,默認(rèn)為3306

,db='test' # 數(shù)據(jù)庫(kù)名稱

,charset='utf8' # 字符編碼

)

cur = conn.cursor() # 生成游標(biāo)對(duì)象

#=============刪除語(yǔ)句===============================

sql="select * from `student` " # SQL語(yǔ)句

#====================================================

try:

cur.execute(sql) # 執(zhí)行插入的sql語(yǔ)句

data = cur.fetchall()

for i in data[:]:

print (i)

conn.commit() # 提交到數(shù)據(jù)庫(kù)執(zhí)行

except:

coon.rollback()# 如果發(fā)生錯(cuò)誤則回滾

conn.close() # 關(guān)閉數(shù)據(jù)庫(kù)連接

小型案例

import pymysql

config = {

'host': '127.0.0.1',

'port': 3306,

'user': 'root',

'passwd': 'password',

'charset':'utf8',

}

conn = pymysql.connect(**config)

cursor = conn.cursor()

try:

# 創(chuàng)建數(shù)據(jù)庫(kù)

DB_NAME = 'test_3'

cursor.execute('DROP DATABASE IF EXISTS %s' %DB_NAME)

cursor.execute('CREATE DATABASE IF NOT EXISTS %s' %DB_NAME)

conn.select_db(DB_NAME)

#創(chuàng)建表

TABLE_NAME = 'bankData'

cursor.execute('CREATE TABLE %s(id int primary key,money int(30))' %TABLE_NAME)

# 批量插入紀(jì)錄

values = []

for i in range(20):

values.append((int(i),int(156*i)))

cursor.executemany('INSERT INTO bankData values(%s,%s)',values)

conn.commit()

# 查詢數(shù)據(jù)條目

count = cursor.execute('SELECT * FROM %s' %TABLE_NAME)

print ('total records:{}'.format(cursor.rowcount))

# 獲取表名信息

desc = cursor.description

print ("%s %3s" % (desc[0][0], desc[1][0]))

cursor.scroll(10,mode='absolute')

results = cursor.fetchall()

for result in results:

print (result)

except:

import traceback

traceback.print_exc()

# 發(fā)生錯(cuò)誤時(shí)會(huì)滾

conn.rollback()

finally:

# 關(guān)閉游標(biāo)連接

cursor.close()

# 關(guān)閉數(shù)據(jù)庫(kù)連接

conn.close()

綜合案例

FIFA球員信息系統(tǒng)

from pymysql import *

class Mysqlpython:

def __init__(self, database='test', host='127.0.0.1', user="root",

password='password', port=3306, charset="utf8"):

self.host = host

self.user = user

self.password = password

self.port = port

self.database = database

self.charset = charset

# 數(shù)據(jù)庫(kù)連接方法:

def open(self):

self.db = connect(host=self.host, user=self.user,

password=self.password, port=self.port,

database=self.database,

charset=self.charset)

# 游標(biāo)對(duì)象

self.cur = self.db.cursor()

# 數(shù)據(jù)庫(kù)關(guān)閉方法:

def close(self):

self.cur.close()

self.db.close()

# 數(shù)據(jù)庫(kù)執(zhí)行操作方法:

def Operation(self, sql):

try:

self.open()

self.cur.execute(sql)

self.db.commit()

print("ok")

except Exception as e:

self.db.rollback()

print("Failed", e)

self.close()

# 數(shù)據(jù)庫(kù)查詢所有操作方法:

def Search(self, sql):

try:

self.open()

self.cur.execute(sql)

result = self.cur.fetchall()

return result

except Exception as e:

print("Failed", e)

self.close()

def Insert():#如何從外面將數(shù)據(jù)錄入到sql語(yǔ)句中

ID = int(input("請(qǐng)輸入球員編號(hào):"))

people_name = input("請(qǐng)輸入球員名字:")

PAC = int(input("請(qǐng)輸入速度評(píng)分:"))

DRI = int(input("請(qǐng)輸入盤(pán)帶評(píng)分:"))

SHO = int(input("請(qǐng)輸入射門(mén)評(píng)分:"))

DEF = int(input("請(qǐng)輸入防守評(píng)分:"))

PAS = int(input("請(qǐng)輸入傳球評(píng)分:"))

PHY = int(input("請(qǐng)輸入身體評(píng)分:"))

score =(PAC+DRI+SHO+DEF+PAS+PHY)/6

sql_insert = "insert into FIFA(ID, people_name, PAC,DRI,SHO,DEF, PAS, PHY, score) values(%d,'%s',%d,%d,%d,%d,%d,%d,%d)"%(ID, people_name, PAC,DRI,SHO,DEF, PAS, PHY, score)

print(people_name)

return sql_insert

def Project():

print("球員的能力評(píng)分有:")

list=['速度','盤(pán)帶','射門(mén)','防守','傳球','身體','綜合']

print(list)

def Exit():

print("歡迎下次使用!!!")

exit()

def Search_choice(num):

date = Mysqlpython()

date.open()

if num=="2":

# 1.增加操作

sql_insert = Insert()

date.Operation(sql_insert)

print("添加成功!")

Start()

elif num=="1":

# 2.查找數(shù)據(jù),其中order by 是為了按什么順序輸出,asc 是升序輸出,desc降序輸出

input_date=input("請(qǐng)選擇您想要以什么格式輸出:默認(rèn)升序排列1.球員編號(hào),2.速度,3.盤(pán)帶,4.射門(mén), 5.防守, 6.傳球, 7.身體 , 8.綜合 ")

if input_date=="1":

sql_search = "select * from FIFA order by ID asc"

elif input_date=="2":

sql_search = "select * from FIFA order by PAC asc"

elif input_date=="3":

sql_search = "select * from FIFA order by DRI asc"

elif input_date=="4":

sql_search = "select * from FIFA order by SHO asc"

elif input_date=="5":

sql_search = "select * from FIFA order by DEF asc"

elif input_date=="6":

sql_search = "select * from FIFA order by PAS asc"

elif input_date=="7":

sql_search = "select * from FIFA order by PHY asc"

elif input_date=="8":

sql_search = "select * from FIFA order by PHY score"

else:

print("請(qǐng)重新輸入!")

result = date.Search(sql_search)

print(" 編號(hào) 姓名 速度 盤(pán)帶 射門(mén) 防守 傳球 身體 綜合 ")

for str in result:

print(str)

Start()

elif num=="3":

Project()

Start()

elif num=="4":

del_num=input("請(qǐng)輸入您要?jiǎng)h除球員的編號(hào):")

sql_delete="delete from FIFA where id=%s"%del_num

date.Operation(sql_delete)

print("刪除成功!")

Start()

elif num=="5":

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

若不方便掃碼,搜微信號(hào):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)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測(cè)極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說(shuō)明請(qǐng)參見(jiàn):http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".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 = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+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); }