Python實(shí)現(xiàn)mysql數(shù)據(jù)庫更新表數(shù)據(jù)接口的功能
前言
昨天,因?yàn)轫?xiàng)目需求要添加表的更新接口,來存儲預(yù)測模型訓(xùn)練的數(shù)據(jù),所以自己寫了一段代碼實(shí)現(xiàn)了該功能,在開始之前,給大家分享python 操作mysql數(shù)據(jù)庫基礎(chǔ):
#coding=utf-8
import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
)
cur = conn.cursor()
#創(chuàng)建數(shù)據(jù)表
#cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
#插入一條數(shù)據(jù)
#cur.execute("insert into student values('2','Tom','3 year 2 class','9')")
#修改查詢條件的數(shù)據(jù)
#cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
#刪除查詢條件的數(shù)據(jù)
#cur.execute("delete from student where age='9'")
cur.close()
conn.commit()
conn.close()
>>> conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)
Connect() 方法用于創(chuàng)建數(shù)據(jù)庫的連接,里面可以指定參數(shù):用戶名,密碼,主機(jī)等信息。
這只是連接到了數(shù)據(jù)庫,要想操作數(shù)據(jù)庫需要創(chuàng)建游標(biāo)。
>>> cur = conn.cursor()
通過獲取到的數(shù)據(jù)庫連接conn下的cursor()方法來創(chuàng)建游標(biāo)。
>>> cur.execute("create table student(id int ,name varchar(20),class varchar(30),age varchar(10))")
通過游標(biāo)cur 操作execute()方法可以寫入純sql語句。通過execute()方法中寫如sql語句來對數(shù)據(jù)進(jìn)行操作。
>>>cur.close()
cur.close() 關(guān)閉游標(biāo)
>>>conn.commit()
conn.commit()方法在提交事物,在向數(shù)據(jù)庫插入一條數(shù)據(jù)時必須要有這個方法,否則數(shù)據(jù)不會被真正的插入。
>>>conn.close()
Conn.close()關(guān)閉數(shù)據(jù)庫連接
下面開始本文的正文:
Python實(shí)現(xiàn)mysql更新表數(shù)據(jù)接口
示例代碼
# -*- coding: utf-8 -*-
import pymysql
import settings
class mysql(object):
def __init__(self):
self.db = None
def connect(self):
self.db = pymysql.connect(host=settings.ip, port=settings.port, user=settings.mysql_user, passwd=settings.mysql_passwd, db=settings.database, )
# print("connect is ok")
# return 1
def disconnect(self):
self.db.close()
# return -1
def create_table(self, tablename, columns, spec='time'):
"""
:param tablename:
:param spec:
:param columns: 列表[]
:return:
"""
type_data = ['int', 'double(10,3)']
cursor = self.db.cursor()
sql="create table %s("%(tablename,)
sqls=[]
for col in columns:
#判斷是否time_num
if col==spec:
sqls.append('%s %s primary key'%(col,type_data[0]))
else:
sqls.append('%s %s'%(col,type_data[1]))
sqlStr = ','.join(sqls)
sql+=sqlStr+')'
try:
cursor.execute(sql)
print("Table %s is created"%tablename)
except:
self.db.rollback()
def is_table_exist(self, tablename,dbname):
cursor=self.db.cursor()
sql="select table_name from information_schema.TABLES where table_schema='%s' and table_name = '%s'"%(dbname,tablename)
#results="error:Thie table is not exit"
try:
cursor.execute(sql)
results = cursor.fetchall() #接受全部返回行
except:
#不存在這張表返回錯誤提示
raise Exception('This table does not exist')
if not results:
return None
else :
return results
# print datas
def insert_mysql_with_json(self, tablename, datas):
"""
:param tablename:
:param datas:字典{(key: value),.....}
:return:
"""
# keys = datas[0]
keys = datas[0].keys()
keys = str(tuple(keys))
keys = ''.join(keys.split("'")) # 用' 隔開
print(keys)
ret = []
for dt in datas:
values = dt.values() ## ‘str' object has no attribute#
sql = "insert into %s" % tablename + keys
sql = sql + " values" + str(tuple(values))
ret.append(sql)
# print("1")
# print keys insert into %tablename dat[i] values str[i]
self.insert_into_sql(ret)
print("1")
def insert_into_sql(self,sqls):
cursor = self.db.cursor()
for sql in sqls:
# 執(zhí)行sql語句
try:
cursor.execute(sql)
self.db.commit()
# print("insert %s" % sql, "success.")
except:
# Rollback in case there is any error
self.db.rollback()
#找列名
def find_columns(self, tablename):
sql = "select COLUMN_NAME from information_schema.columns where table_name='%s'" % tablename
cursor = self.db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
except:
raise Exception('hello')
return tuple(map(lambda x: x[0], results))
def find(self, tablename, start_time, end_time, fieldName=None):
"""
:param tablename: test_scale1015
:param fieldName: None or (columns1010, columns1011, columns1012, columns1013, time)
:return:
"""
cursor = self.db.cursor()
sql = ''
if fieldName==None:
fieldName = self.find_columns(tablename)
sql = "select * from %s where time between %s and %s" % (tablename, str(start_time), str(end_time))
# print('None')
else:
fieldNameStr = ','.join(fieldName)
sql = "select %s from %s where time between %s and %s" % (
fieldNameStr, tablename, str(start_time), str(end_time))
# print('sm')
try:
cursor.execute(sql)
results = cursor.fetchall()
except:
raise Exception('hello')
return fieldName, results,
#樣例 data = [{'time':123321,'predict':1.222},{'time':123322,'predict':1.223},{'time':123324,'predict':1.213}]
def updata(self,datas, tablename):
cursor = self.db.cursor()
columns = []
for data in datas:
for i in data.keys():
columns.append(i)
# print(columns)
break
# columns_2=columns[:]
db.connect()
if db.is_table_exist(settings.tablename_2, settings.database):
# exists
# pass
for col in columns:
if col != 'time':
sql = "alter table %s add column %s double(10,3);" % (settings.tablename_2, col)
try:
cursor.execute(sql)
print("%s is altered ok" % (col))
except:
print("alter is failed")
ret = []
for i in datas:
col = []
for ii in i.keys():
col.append(ii)
#time = col[0] and predict = col[1]
time_data = i[col[0]]
predic_data = i[col[1]]
sql = "update %s set %s='%s'where %s=%s"%(settings.tablename_2,col[1],predic_data,col[0],time_data)
ret.append(sql)
self.insert_into_sql(ret)
# db.insert_mysql_with_json(tablename, datas)
else:
# no exists
db.create_table(settings.tablename_2, columns)
db.insert_mysql_with_json(settings.tablename_2, datas)
db = mysql()
其中update()函數(shù),是新添加的接口:
傳入的data的樣例 data = [{'time':123321,'predict':1.222},{'time':123322,'predict':1.223},{'time':123324,'predict':1.213}] 這樣子的。
一個列表里有多個字典,每個字典有time和predict。如果需要存predict_2,predict_3的時候,則實(shí)現(xiàn)更新操作,否則,只進(jìn)行創(chuàng)表和插入數(shù)據(jù)的操作~~~~~~
看起來是不是很簡單~~~~~~
這個接口還沒有進(jìn)行優(yōu)化等操作,很冗余~~~~
畢竟項(xiàng)目還在測試階段,等先跑通了,在考慮優(yōu)化吧~~~~~~
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
基于python+opencv調(diào)用電腦攝像頭實(shí)現(xiàn)實(shí)時人臉眼睛以及微笑識別
這篇文章主要為大家詳細(xì)介紹了基于python+opencv調(diào)用電腦攝像頭實(shí)現(xiàn)實(shí)時人臉眼睛以及微笑識別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
pytorch從csv加載自定義數(shù)據(jù)模板的操作
這篇文章主要介紹了pytorch從csv加載自定義數(shù)據(jù)模板的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
python實(shí)現(xiàn)根據(jù)文件格式分類
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)根據(jù)文件格式分類,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-10-10
探秘TensorFlow 和 NumPy 的 Broadcasting 機(jī)制
這篇文章主要介紹了探秘TensorFlow 和 NumPy 的 Broadcasting 機(jī)制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
Python中pip安裝非PyPI官網(wǎng)第三方庫的方法
這篇文章主要介紹了Python中pip安裝非PyPI官網(wǎng)第三方庫的方法,pip最新的版本(1.5以上的版本), 出于安全的考 慮,pip不允許安裝非PyPI的URL,本文就給出兩種解決方法,需要的朋友可以參考下2015-06-06
MacBook m1芯片采用miniforge安裝python3.9的方法示例
這篇文章主要介紹了MacBook m1芯片采用miniforge安裝python3.9的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
python中while和for的區(qū)別總結(jié)
在本篇內(nèi)容里小編給大家分享的是關(guān)于python中while和for的區(qū)別以及相關(guān)知識點(diǎn),需要的朋友們可以學(xué)習(xí)下。2019-06-06
python判斷計(jì)算機(jī)是否有網(wǎng)絡(luò)連接的實(shí)例
今天小編就為大家分享一篇python判斷計(jì)算機(jī)是否有網(wǎng)絡(luò)連接的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

