Python 3.5 MySQL支持庫
https://github.com/PyMySQL/PyMySQL/
這個PyMySQL 值得關注,最近一天前更新。
1、安裝這個庫 pip install PyMySQL 或 sudo pip install PyMySQL
2、先創建一個資料庫,再創建一個users 表。
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,`email` varchar(255) COLLATE utf8_bin NOT NULL,`password` varchar(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_binAUTO_INCREMENT=1 ;3、Python 演示代碼。
import pymysql.cursorsnn# Connect to the databasenconnection = pymysql.connect(host=localhost,n user=user,n password=passwd,n db=db,n charset=utf8mb4,n cursorclass=pymysql.cursors.DictCursor)nntry:n with connection.cursor() as cursor:n # Create a new recordn sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"n cursor.execute(sql, (webmaster@python.org, very-secret))nn # connection is not autocommit by default. So you must commit to saven # your changes.n connection.commit()nn with connection.cursor() as cursor:n # Read a single recordn sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"n cursor.execute(sql, (webmaster@python.org,))n result = cursor.fetchone()n print(result)nfinally:n connection.close()n
結果為:{password: very-secret, id: 1}
推薦閱讀:
※matplotlib畫圖如何高質量導入到word中?
※python封裝阿里雲API
※pymongo 查詢時,顯示循環不同,為何效率相差百倍?
※《Django By Example》第八章 中文翻譯
TAG:Python |