將資料存入mysql中
阿新 • • 發佈:2018-11-23
import pymysql import warnings # 忽略警告 warnings.filterwarnings("ignore") # 連線資料庫 db = pymysql.connect("localhost", 'root', "123456", charset="utf8") # 建立遊標 cursor = db.cursor() # 建立資料庫,如果存在,就不建立 c_db = "create database if not exists spiderdb charset utf8" # 使用該資料庫 u_db = "use spiderdb" # 建立表,如果存在,則不建立c_tab = "create table if not exists t1(id int primary key auto_increment,\ name varchar(50))" ins = "insert into t1 values(1)" try: cursor.execute(c_db) cursor.execute(u_db) cursor.execute(c_tab) cursor.execute(ins) # 提交 db.commit() except Warning: pass # 光閉遊標 cursor.close()# 光閉資料庫 db.close()