使用 PyMySQL 連線資料庫,並實現簡單的增刪改查
阿新 • • 發佈:2018-12-08
首先需要
import pymysql
1.連線資料庫
#獲取資料庫連線
def getDBConn():
conn = pymysql.connect(
host = 'localhost',
port = 3306,
user = 'root',
password = '123',
db = 'insurancedata',
charset = 'utf8'
)
return conn
2.關閉資料庫連線
def closeConn(cursor,conn): if cursor: cursor.close() if conn: conn.close()
3.插入資料
#插入資料 def inset_To_url_table(): try: conn = getDBConn() cursor = conn.cursor() sql = "INSERT INTO url_table(url,url_state)VALUES(%s,%s)" url = "http://baidu.com/item/123" status = "0" params = (url,status) cursor.execute(sql,params) conn.commit() except: conn.rollback() print('insert error') finally: closeConn(cursor,conn)
4.查詢資料
def select_url_table(URL): try: conn = getDBConn() cursor = conn.cursor() sql = "SELECT url_state from url_table WHERE url = URL" cursor.execute(sql) url_state = cursor.fetchall()[0][0] return url_state except: print('select error') return None finally: closeConn(cursor,conn)