python3基本上使用pymysql進行操作。下面是乙個簡單操作的小例子,大家可以看下。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pymysql
class mydb():
def __init__(self, host="127.0.0.1", username="root", password="123456", port=3306, database="test"):
"""類例化,處理一些連線操作
"""self.host = host
self.username = username
self.password = password
self.database = database
self.port = port
self.cur = none
self.con = none
try:
self.con = pymysql.connect(host=self.host, user=self.username, password=self.password,
port=self.port, database=self.database)
self.cur = self.con.cursor()
except exception as err:
raise exception("資料庫連線錯誤,請檢查連線配置.", err)
def close(self):
"""結束查詢和關閉連線
"""self.con.close()
def create_table(self, sql_str):
"""建立資料表"""
try:
self.cur.execute(sql_str)
except exception as e:
print(e)
def query_formatrs(self, sql_str):
"""查詢資料,返回乙個列表,裡面的每一行是乙個字典,帶欄位名
cursor 為連線游標
sql_str為查詢語句
"""try:
self.cur.execute(sql_str)
rows = self.cur.fetchall()
r =
for x in rows:
return r
except:
return false
def query(self, sql_str):
"""查詢資料並返回
cursor 為連線游標
sql_str為查詢語句
"""try:
self.cur.execute(sql_str)
rows = self.cur.fetchall()
return rows
except exception as err:
return false
def execute_update_insert(self, sql):
"""插入或更新記錄 成功返回最後的id
"""self.cur.execute(sql)
self.con.commit()
return self.cur.lastrowid
if __name__ == "__main__":
mydb = mydb()
# 建立表
mydb.create_table('drop table if exists `user`; create table user (id varchar(20) primary key, name varchar(20))')
# 插入資料
mydb.execute_update_insert("insert into user (name) values ('zhangsan')")
# 查詢資料表
mydb_new = mydb()
results = mydb.query("select * from user")
print(results)
for row in results:
ids = row[0]
name = row[1]
print("id=%s,name=%s" % (ids, name))
# 關閉資料庫
mydb.close()
Python 下 pymysql 資料庫重新連線
這是pymysql的問題吧?為什麼超時時間設定不起作用,為什麼不自動重連一下呢?好在提供了乙個 ping 方法 ping self,reconnect true check if the server is alive.param reconnect if the connection is clo...
python3 安裝pymysql連線模組
在使用 pymysql 之前,我們需要確保 pymysql 已安裝。如果還未安裝,我們可以使用以下命令安裝最新版的 pymysql pip install pymysql如果你的系統不支援 pip 命令,可以使用以下方式安裝 py install2 如果需要制定版本號,可以使用 curl 命令來安裝...
python3使用pymysql運算元據庫
導入庫 import pymysql 一 增 def insert value 開啟資料庫連線 使用者名稱 密碼 資料庫名 db pymysql.connect localhost username password database 使用 cursor 方法建立乙個游標物件 cursor curs...