- 首先導入模塊
import pymysql.cursors
- 鏈接數據庫
- 獲取游標
connection = pymysql.connect(host='127.0.0.1',
user='root',
password='896641606',
db = 'newtable',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
- 創建表
TABLEONE
此處要大寫 不知為何?不需要引號
sql = """CREATE TABLE IF NOT EXISTS TABLEONE (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_bin NOT NULL,
`vote_count` int(255) COLLATE utf8_bin NOT NULL,
`answer_count` int(255) COLLATE utf8_bin NOT NULL,
`scan_count` int(255) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin
AUTO_INCREMENT=1 ;"""
creatResult = cursor.execute(sql)
- 插入數據
- 需要注意的是雖然創建表的時候定義的 三列
vote_count
answer_count
scan_count
是int
類型 但是拼接 sql 語句的時候仍然要用%s
否則插入不報錯,但是不成功.
sql = "INSERT INTO `TABLEONE` (`title`, vote_count, answer_count, scan_count) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, ('webmaster@python.org', -1,1,30))
connection.commit()
源文檔地址: http://pymysql.readthedocs.io/en/latest/user/examples.html