Python操作MySQL數(shù)據(jù)庫的簡單步驟分享
現(xiàn)在Python越來越被大眾所使用,特別是進入AI人工智能時代,對編程要求更加高效根據(jù)快捷,所以Python也經(jīng)常成為人工智和大數(shù)據(jù)編程的重要語音。既然是編程語言就多多少少會需求對數(shù)據(jù)進行操作,這一篇我們帶大家使用python對mysql進行的操作。
別的不說,直接上代碼
MySQL 建表建表的時候,遇到一些坑,沒有解決,如修改 MySQL 的默認引擎,default-storage-engine=InnoDB;執(zhí)行報錯 。。。無奈
use mybatistable;drop table Test;-- INNODB 支持事務 -- Mysql 默認的引擎是 MyISAM ,不支持事務操作-- 在創(chuàng)建 mysql 表時,最好指定表使用的引擎 -- 或者直接修改Mysql 默認的數(shù)據(jù)庫引擎為 InnoDB-- default-storage-engine=InnoDB; 執(zhí)行報錯 。。。無奈create table Test( id int(10) not null auto_increment, name varchar(20) not null, password varchar(30) not null, constraint pk_id primary key(id), constraint uk_name unique(name))engine=InnoDB charset=utf8;-- 查看表的引擎show create table Test;-- 更新表的引擎 ,執(zhí)行報錯-- alter table Test type = InnoDB; insert into Test values(default,’小紅’,123);insert into Test values(default,’小李’,123);insert into Test values(default,’小趙’,123);insert into Test values(default,’小軍’,123);insert into Test values(default,’小方’,123);select * from Test;python 操作 MySQL
import pymysql’’’ 連接 mysql 數(shù)據(jù)庫的步驟 fetchall 接受全部的返回結(jié)果行 PS:只有 innodb 類型的表才可以設置 autocommit;’’’def connectMySql(): host = ’127.0.0.1’ username = ’root’ password = ’root’ # dbName = ’MyBatistable’ # 獲得數(shù)據(jù)庫連接對象 conn = pymysql.connect(host,username,password) #關(guān)閉數(shù)據(jù)庫的自動提交事務 conn.autocommit(False) # 選擇要操作的數(shù)據(jù)庫 conn.select_db(’MyBatistable’) #覆蓋之前操作的數(shù)據(jù)庫名 # 獲得游標 cursor = conn.cursor() #定義 SQL 語句 sql = ’select * from Test’ sql1 = ’insert into test values(default,'小鍋','120')’ sql2 = ’update test set name='小庫2' where id = 2’ sql3 = ’delete from test where id = 2’ #執(zhí)行 SQL 語句 # row = cursor._query(sql) #執(zhí)行 execute 方法,返回影響的行數(shù) row = cursor.execute(sql1) print(’row type:’,type(row)) print(’受影響的行數(shù)為:’,row) if row > 0:conn.commit() # 提交事務print(’SUCCESS’) else:conn.rollback() # 回滾事務print(’Failure’) #使用DQL ,返回結(jié)果集,以元組的形式 nums = cursor.fetchall() print(’nums Type:’,type(nums)) #處理結(jié)果集 if nums != () :for num in nums: print(’--’,num)if __name__ == ’__main__’: connectMySql()總結(jié)
Python 操作 MySQL 時,由于MySQL 默認使用時 MyISAM 引擎,不支持事務操作。而在Python操作 Mysql 中關(guān)閉自動提交事務,發(fā)現(xiàn)并沒有卵用,然后到網(wǎng)上百度說,Mysql 中 InnoDB 支持事務,然后我查找一哈我自己表的引擎發(fā)現(xiàn)是 MyISAM ,欲哭無淚啊。然后我就重新開始建表,測試。
到此這篇關(guān)于Python操作MySQL數(shù)據(jù)庫的簡單步驟的文章就介紹到這了,更多相關(guān)Python操作MySQL數(shù)據(jù)庫內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
