# 資料庫操作
import pymysql
class mysqlhelper(object):
def __init__(self, host, user, pw, db):
"""連線資料庫,建立游標"""
# self.conn = pymysql.connect(host='localhost', user='root', password='111212', database='students')
self.host, self.user, self.pw, self.db = host, user, pw, db
# 定製游標 拿出資料成字典
# self.cursor = self.conn.cursor(cursor=pymysql.cursors.dictcursor)
def __getconnect(self):
if not self.db:
raise (nameerror, "沒有資料庫資訊")
self.conn = pymysql.connect(host=self.host, user=self.user, password=self.pw, database=self.db)
cursor = self.conn.cursor(cursor=pymysql.cursors.dictcursor)# 定製游標 拿出資料成字典 預設元組方式拿出資料
if not cursor:
raise (nameerror, "資料庫連線失敗")
else:
return cursor
def execqueryall(self, sql, args=()): # sql即sql語句,args為sql所需引數
cursor = self.__getconnect()
result = cursor.execute(sql, args)
gdata = cursor.fetchall() # 獲取所有符合sql select語句的值
cursor.close() # 關閉游標
self.conn.close() # 關閉連線
return [result, gdata]
def execqueryone(self, sql, args=()):
cursor = self.__getconnect()
result = cursor.execute(sql, args)
gdata = cursor.fetchone() # 獲取乙個符合sql select語句的值
cursor.close()
self.conn.close()
return [result, gdata]
def execnonquerymany(self, sql, args=()):
cursor = self.__getconnect()
result = cursor.executemany(sql, args)
self.conn.commit() # update、delete、insert into 多條提交
lastmod = cursor.lastrowid # 獲取最新插入資料的自增值
cursor.close()
self.conn.close()
return [result, lastmod]
def execnonqueryone(self, sql, args=()):
cursor = self.__getconnect()
result = cursor.execute(sql, args)
self.conn.commit() # update、delete、insert into 單挑提交
lastrowid = cursor.lastrowid # 獲取最新插入資料的自增值
cursor.close()
self.conn.close()
return [result, lastrowid]
呼叫:
mysqlop = mysqlhelper("localhost","root","111212","students")
getplanname = mysqlop.execqueryone(sql='select planname from taskplan where planname=%s limit 1',args=(tasklist[0]['planname']))
print(getplanname)
python操作mysql查詢資料
首先需要連線資料庫,然後才查詢出資料。例如下表名字為 sinauser iduse id use name11 db12 2db233 db3class database def init self self.conn mysqldb.connect 連線資料庫 host 連線你要取出資料庫的ip,...
python操作MySQL資料庫
堅持每天學一點,每天積累一點點,作為自己每天的業餘收穫,這個文章是我在吃飯的期間寫的,利用自己零散的時間學了一下python操作mysql,所以整理一下。我採用的是mysqldb操作的mysql資料庫。先來乙個簡單的例子吧 import mysqldb try conn mysqldb.connec...
Python操作Mysql資料庫
coding utf8 author yangjing import mysqldb 查詢。def select host user root password port 3306,db sql connect mysqldb.connect host host,user user,passwd p...