Python3.X 與 PyMysql

1.沒有安裝PyMysql,進行安裝

?pip3 install PyMysql

2.連接數(shù)據(jù)庫

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

def db_connect():

? ? try:

? ? ? ? # 打開數(shù)據(jù)庫連接

? ? ? ? db = pymysql.connect("localhost", "root", "123456", "test")

? ? ? ? print('Database connection success')

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

? ? ? ? db.close()

? ? except Exception as e:

? ? ? ? print("Database connection failure.error:%s"% e)

def main():

? ? db_connect()

if __name__ == "__main__":

? ? main()


3.創(chuàng)建表

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

def create_table():

? ? # 打開數(shù)據(jù)庫連接

? ? db = pymysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="test", charset='utf8')

? ? # 使用cursor()方法創(chuàng)建一個游標對象cursor

? ? cursor = db.cursor()

? ? # 使用execute()方法執(zhí)行SQL查詢

? ? cursor.execute("DROP TABLE IF EXISTS member")

? ? # 使用預處理語句創(chuàng)建表

? ? sql = """CREATE TABLE member(

? ? ? ? ? ? `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',

? ? ? ? ? ? `nickname` char(20) NOT NULL COMMENT '昵稱',

? ? ? ? ? ? `realname` char(20) NOT NULL COMMENT '真實姓名',

? ? ? ? ? ? `birth` datetime DEFAULT NULL COMMENT '出生年月日',

? ? ? ? ? ? `hobby` varchar(255) NOT NULL COMMENT '愛好',

`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',

? ? ? ? ? ? `edit_time` datetime DEFAULT NULL COMMENT '編輯時間',

? ? ? ? ? ? PRIMARY KEY(`id`),

? ? ? ? ? ? KEY `nickname` (`nickname`),

? ? ? ? ? ? KEY `realname` (`realname`)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='會員表'"""

? ? try:

? ? ? ? cursor.execute(sql)

? ? ? ? print("CREATE TABLE SUCCESS.")

? ? except Exception as e:

? ? ? ? print("CREATE TABLE FAILED,CASE:%S",e)

? ? finally:

? ? ? ? # 關(guān)閉數(shù)據(jù)庫

? ? ? ? db.close()

def main():

? ? create_table()

4.批量插入數(shù)據(jù)

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

def insert():

? ? # 打開數(shù)據(jù)庫連接

? ? db = pymysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="test", charset='utf8')

? ? # 使用cursor()方法創(chuàng)建一個游標對象cursor

? ? cursor = db.cursor()

? ? data =? [

? ? ? ? ? ? ? ? ['二哥', '王力宏', '1992-01-01 08:00:00','吉他'],

? ? ? ? ? ? ? ? ['春哥', '陳小春', '1990-01-01 08:00:00', '古惑仔'],

? ? ? ? ? ? ? ? ['穎寶' ,'趙麗穎', '1995-01-01 08:00:00', '武俠劇']

? ? ? ? ? ? ]

? ? # SQL 插入語句

? ? sql = """INSERT INTO member(`nickname`,`realname`, `birth`, `hobby`) VALUES(%s, %s, %s, %s)"""

? ? try:

? ? ? ? # 批量插入數(shù)據(jù),比循環(huán)插入快

? ? ? ? cursor.executemany(sql,data)

? ? ? ? # 數(shù)據(jù)提交

? ? ? ? db.commit()

? ? ? ? print("INSERT DATA SUCCESS.")

? ? except Exception as e:

? ? ? ? print("INSERT DATA FAILED,CASE:%S",e)

? ? ? ? # 數(shù)據(jù)回滾

? ? ? ? db.rollback()

? ? finally:

? ? ? ? # 關(guān)閉數(shù)據(jù)庫

? ? ? ? db.close()

def main():

? ? insert()

if __name__ == "__main__":

? ? main()

5.數(shù)據(jù)查詢

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

def select():

? ? # 打開數(shù)據(jù)庫連接

? ? db = pymysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="test", charset='utf8')

? ? # 使用cursor()方法創(chuàng)建一個游標對象cursor

? ? cursor = db.cursor()

? ? # SQL 查詢語句

? ? sql = """SELECT * FROM member WHERE birth > %s"""

? ? try:

? ? ? ? # 執(zhí)行SQL語句

? ? ? ? cursor.execute(sql,('1990-01-01 08:00:00'))

? ? ? ? # 獲取所有記錄列表

? ? ? ? results = cursor.fetchall()

? ? ? ? print( results )

? ? ? ? return

? ? ? ? for index, value in enumerate(results):

? ? ? ? ? ? print("昵稱:%s? 真實姓名:%s? 生日:%s \r\n" % ( value[1], value[2], value[3] ))

? ? except Exception as e:

? ? ? ? print("SELECT DATA FAILED,ERROR:%S",e)

? ? finally:

? ? ? ? # 關(guān)閉數(shù)據(jù)庫

? ? ? ? db.close()

def main():

? ? select()

if __name__ == "__main__":

? ? main()

6.數(shù)據(jù)更改

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

import datetime

def update():

? ? # 打開數(shù)據(jù)庫連接

? ? db = pymysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="test", charset='utf8')

? ? # 使用cursor()方法創(chuàng)建一個游標對象cursor

? ? cursor = db.cursor()

? ? # SQL 查詢語句

? ? sql = """UPDATE member SET realname = %s , edit_time = %s? WHERE id = %s"""

? ? try:

? ? ? ? # 執(zhí)行SQL語句

? ? ? ? result = cursor.execute(sql,("王小宏", datetime.datetime.now(), 1))

? ? ? ? if result == 1:

? ? ? ? ? ? # 數(shù)據(jù)提交

? ? ? ? ? ? db.commit()

? ? ? ? ? ? print("UPDATE DATA SUCCESS")

? ? ? ? else:

? ? ? ? ? ? # 拋出異常

? ? ? ? ? ? raise NameError('ValueError')

? ? except Exception as e:

? ? ? ? # 數(shù)據(jù)回滾

? ? ? ? db.rollback()

? ? ? ? print("UPDATE DATA FAILED,ERROR:%S",e)

? ? finally:

? ? ? ? # 關(guān)閉數(shù)據(jù)庫

? ? ? ? db.close()

def main():

? ? update()

if __name__ == "__main__":

? ? main()

7.刪除數(shù)據(jù)

#! /usr/bin/python

# -*-coding:UTF-8-*-

import pymysql

import datetime

def update():

? ? # 打開數(shù)據(jù)庫連接

? ? db = pymysql.connect(host="localhost", port=3306, user="root", passwd="123456", db="test", charset='utf8')

? ? # 使用cursor()方法創(chuàng)建一個游標對象cursor

? ? cursor = db.cursor()

? ? # SQL 查詢語句

? ? sql = """DELETE FROM member WHERE id = %s"""

? ? try:

? ? ? ? # 執(zhí)行SQL語句

? ? ? ? result = cursor.execute(sql,(1))

? ? ? ? if result == 1:

? ? ? ? ? ? # 數(shù)據(jù)提交

? ? ? ? ? ? db.commit()

? ? ? ? ? ? print("DELETE DATA SUCCESS")

? ? ? ? else:

? ? ? ? ? ? # 拋出異常

? ? ? ? ? ? raise NameError('ValueError')

? ? except Exception as e:

? ? ? ? # 數(shù)據(jù)回滾

? ? ? ? db.rollback()

? ? ? ? print("DELETE DATA FAILED,ERROR:%S",e)

? ? finally:

? ? ? ? # 關(guān)閉數(shù)據(jù)庫

? ? ? ? db.close()

def main():

? ? update()

if __name__ == "__main__":

? ? main()


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容