前言
現(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 支持事務(wù)
-- Mysql 默認的引擎是 MyISAM ,不支持事務(wù)操作
-- 在創(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 類型的表才可以設(shè)置 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ù)庫的自動提交事務(wù)
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() # 提交事務(wù)
print('SUCCESS')
else:
conn.rollback() # 回滾事務(wù)
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 引擎,不支持事務(wù)操作。而在Python操作 Mysql 中關(guān)閉自動提交事務(wù),發(fā)現(xiàn)并沒有卵用,然后到網(wǎng)上百度說,Mysql 中 InnoDB 支持事務(wù),然后我查找一哈我自己表的引擎發(fā)現(xiàn)是 MyISAM ,欲哭無淚啊。然后我就重新開始建表,測試。
到此這篇關(guān)于Python操作MySQL數(shù)據(jù)庫的簡單步驟的文章就介紹到這了,更多相關(guān)Python操作MySQL數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- MySQL 重命名表的操作方法及注意事項
- MySQL數(shù)據(jù)庫重命名的快速且安全方法(3種)
- mysql事件之修改事件(ALTER EVENT)、禁用事件(DISABLE)、啟用事件(ENABLE)、事件重命名及數(shù)據(jù)庫事件遷移操作詳解
- 詳解MYSQL中重命名procedure的一種方法
- MySQL中使用SQL語句對字段進行重命名
- mysql數(shù)據(jù)庫重命名語句分享
- 教你怎么用Python操作MySql數(shù)據(jù)庫
- 用python開發(fā)一款操作MySQL的小工具
- Python基礎(chǔ)之操作MySQL數(shù)據(jù)庫
- Python聊天室?guī)Ы缑鎸崿F(xiàn)的示例代碼(tkinter,Mysql,Treading,socket)
- Python使用sql語句對mysql數(shù)據(jù)庫多條件模糊查詢的思路詳解
- Python中tkinter+MySQL實現(xiàn)增刪改查
- 運用Python快速的對MySQL數(shù)據(jù)庫進行重命名