python3 - 用pymysql操作數據庫


  • 首先導入模塊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_countint 類型 但是拼接 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM