欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼

 更新時間:2017年12月28日 14:20:37   作者:不論如何未來很美好  
這篇文章主要介紹了python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼,具有一定借鑒價值,需要的朋友可以參考下

本文主要研究的是python3.6連接MySQL和表的創(chuàng)建與刪除的相關(guān)內(nèi)容,具體步驟和代碼如下。

python3.6不支持importMySQLdb改用為importpymysql模塊,需要自行安裝模塊pymysql。

1:python3.6安裝模塊pymysql

命令行安裝pipinstallpymysql

2:python3.6連接mysql數(shù)據(jù)庫

#!/bin/env Python 
# -*- coding:utf-8 -*- 
import pymysql 
conn = pymysql.connect( 
 user="root", 
 password="root@123456", 
 port=3306, 
 host="127.0.0.1", #本地數(shù)據(jù)庫 等同于localhost 
 db="MYSQL", 
 charset="utf8" 
) 
conn.cursor() #獲取對應(yīng)的操作游標(biāo) 

請注意連接數(shù)據(jù)庫時要保證數(shù)據(jù)庫已經(jīng)開啟,否則連接失敗。

表的創(chuàng)建與刪除

操作代碼:

import pymysql 
 
connect = pymysql.connect( #連接數(shù)據(jù)庫服務(wù)器 
 user="root", 
 password="xxxxx", 
 host="127.0.0.1", 
 port=3306, 
 db="MYSQL", 
 charset="utf8" 
 ) 
conn = connect.cursor() #創(chuàng)建操作游標(biāo) 
#你需要一個游標(biāo) 來實現(xiàn)對數(shù)據(jù)庫的操作相當(dāng)于一條線索 
 
#    查看 
conn.execute("SELECT * FROM user") #選擇查看自帶的user這個表 (若要查看自己的數(shù)據(jù)庫中的表先use XX再查看) 
rows = conn.fetchall()  #fetchall(): 接收全部的返回結(jié)果行,若沒有則返回的是表的內(nèi)容個數(shù) int型 
for i in rows: 
 print(i) 
 
#    創(chuàng)建表 
conn.execute("drop database if exists new_database") #如果new_database數(shù)據(jù)庫存在則刪除 
conn.execute("create database new_database") #新創(chuàng)建一個數(shù)據(jù)庫 
conn.execute("use new_database")  #選擇new_database這個數(shù)據(jù)庫 
# sql 中的內(nèi)容為創(chuàng)建一個名為new_table的表 
sql = """create table new_table(id BIGINT,name VARCHAR(20),age INT DEFAULT 1)""" #()中的參數(shù)可以自行設(shè)置 
conn.execute("drop table if exists new_table") # 如果表存在則刪除 
conn.execute(sql) # 創(chuàng)建表 
 
#    刪除 
# conn.execute("drop table new_table") 
 
conn.close()  # 關(guān)閉游標(biāo)連接 
connect.close() # 關(guān)閉數(shù)據(jù)庫服務(wù)器連接 釋放內(nèi)存 

實現(xiàn)以上代碼后進入數(shù)據(jù)庫中查看你會發(fā)現(xiàn)多了一個數(shù)據(jù)庫 new_database其中多了一個new_table表

總結(jié)

以上就是本文關(guān)于python3.6連接MySQL和表的創(chuàng)建與刪除實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論