1. 程式人生 > >python和MYSQL互動

python和MYSQL互動

 PyMySQL 是在 Python3.x 版本中用於連線 MySQL 伺服器的一個庫,Python2中則使用mysqldb。

 

import pymysql

# 開啟資料庫連線
db = pymysql.connect(host="localhost", user="root", password="***",database= "***")

# 使用 cursor() 方法建立一個遊標物件 cursor
cursor = db.cursor()

# 使用 execute() 方法執行 SQL,如果表存在則刪除
cursor.execute("drop table if exists TestTable")

# 使用預處理語句建立表,SQL語句不區分大小寫,習慣小寫。
sql = """create table TestTable(
         name  char(20) not NULL,
         names  char(20),
         age int,  
         sex char(1),
         income float)"""

cursor.execute(sql)   #執行SQL語句

# 關閉資料庫連線
db.close()

 實現如下: