一、安裝
- 經過查資料python3.x不再支持mysqldb。其替代模塊是PyMySQL
用管理員打開cmd
pip3 install PyMySQL
鏈接數據庫創建一個數據庫
mysql -uroot -proot create database python; use python;
創建一個表
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_bin AUTO_INCREMENT=1 ;
寫一個python文件
import pymysql import pymysql.cursors # 鏈接數據庫 connection = pymysql.connect(host='localhost', user='root', password='root', db='python', charset='utf8', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: # 添加一條新的記錄 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ('[email protected]', 'very-secret')) # 提交結果 connection.commit() with connection.cursor() as cursor: # 讀取結果 sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ('[email protected]',)) result = cursor.fetchone() print(result) finally: connection.close()
看到以上結果就代表安裝成功了;
二 、尾巴
1.如有錯誤歡迎大家指出,我會及時更正,有什麼不懂也可以留言提問,互相交流嗎。
2.也許大家覺得這沒什麼,但是我會認真對待,把它當成我的筆記、心得、這樣才能提升自己。