1.安裝mysqlpython
2.安裝pymysql驅動 pip install pymysql mysql
3.建立一張數據表sql
CREATE TABLE `players` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `name` VARCHAR(30) COLLATE utf8_bin NOT NULL, `club` VARCHAR(20) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1;
4.python操做mysql數據庫數據庫
1). 添加數據fetch
import pymysql # 鏈接數據庫 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='root', db='news', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) # 建立遊標 cursor = conn.cursor() # 建立SQL語句並執行 sql = "INSERT INTO `players` (`name`, `club`) VALUES ('James', 'Lakers'), ('Westbrook', 'Thunder')" cursor.execute(sql) #提交sql conn.commit()
其中host爲數據庫的主機IP地址,本地通常爲‘127.0.0.1’, port爲MySQL的默認端口號,通常爲3306,user爲數據的用戶名,password爲數據庫的登陸密碼,db爲數據庫的名稱。spa
cursor()方法建立數據庫遊標。rest
execute()方法執行SQL語句。code
commit()將數據庫的操做真正的提交到數據。blog
2)查詢數據ip
import pymysql # 鏈接數據庫 conn = pymysql.connect( host='127.0.0.1', port=3306, user='root', password='root', db='news', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) # 建立遊標 cursor = conn.cursor() # 建立SQL語句並執行 sql = "SELECT `name`, `club` FROM `players` WHERE `id`='1'" cursor.execute(sql) #單條語句查詢 rest = cursor.fetchone() print(rest) print("---------我是分割線-------------") # 建立SQL語句並執行 sql = "SELECT `name`, `club` FROM `players`" cursor.execute(sql) # 多條語句查詢 rest = cursor.fetchall() for item in rest: print(item)
執行結果:
{'name': 'James', 'club': 'Lakers'} ---------我是分割線------------- {'name': 'James', 'club': 'Lakers'} {'name': 'Westbrook', 'club': 'Thunder'}