Python3數(shù)據(jù)庫操作包pymysql的操作方法
以下代碼實現(xiàn)環(huán)境是mac系統(tǒng),本地配置mysql服務(wù)端和navicat premium客戶端,python環(huán)境是配置了pymysql的anaconda3。
首先,與數(shù)據(jù)庫建立connection和進行操作的原理
(1)通過navicat premium創(chuàng)建testdataset數(shù)據(jù)庫和庫內(nèi)數(shù)據(jù)表test:
CREATE TABLE `test` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2)在test數(shù)據(jù)表里添加數(shù)據(jù)項
(3)jupyter notebook里連接數(shù)據(jù)庫,并對數(shù)據(jù)庫進行操作
import pandas as pd import datetime import pymysql #創(chuàng)建連接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='******', db='testdataset', charset='utf8')#passwd是本地mysql服務(wù)器密碼 conn #Output:<pymysql.connections.Connection at 0x11443e588> #創(chuàng)建游標 cursor = conn.cursor() cursor #Output:<pymysql.cursors.Cursor at 0x11443e2e8> #執(zhí)行SQL,并返回受影響行數(shù) effect_row = cursor.execute("select * from test") effect_row #Output:4 #獲取剩余結(jié)果的第一行數(shù)據(jù) r1=cursor.fetchone() r1 #Output:(1, '李明', 18) name='王天' age=17 sql="select name,age from test where name='%s' and age='%s'" % (name,age) row_count=cursor.execute(sql) row_1 = cursor.fetchone() print(row_count,row_1) #Output:1 ('王天', 17) conn.commit() cursor.close() conn.close()
總結(jié)
以上所述是小編給大家介紹的Python3數(shù)據(jù)庫操作包pymysql的操作方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解
- python3使用PyMysql連接mysql數(shù)據(jù)庫實例
- python?實現(xiàn)?pymysql?數(shù)據(jù)庫操作方法
- python3.6使用pymysql連接Mysql數(shù)據(jù)庫
- 詳解Python的數(shù)據(jù)庫操作(pymysql)
- Python 解析pymysql模塊操作數(shù)據(jù)庫的方法
- Python 中使用 PyMySQL模塊操作數(shù)據(jù)庫的方法
- python數(shù)據(jù)庫操作指南之PyMysql使用詳解
相關(guān)文章
Pandas:Series和DataFrame刪除指定軸上數(shù)據(jù)的方法
今天小編就為大家分享一篇Pandas:Series和DataFrame刪除指定軸上數(shù)據(jù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11在Python中通過threading模塊定義和調(diào)用線程的方法
由于著名的GIL的存在,Python中雖然能創(chuàng)建多條線程,但卻不能同時執(zhí)行...anyway,這里我們還是來學習一下在Python中通過threading模塊定義和調(diào)用線程的方法2016-07-07用python3讀取python2的pickle數(shù)據(jù)方式
今天小編就為大家分享一篇用python3讀取python2的pickle數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12