常見的資料庫操作的方法封裝:
import pymysql
class dbfunc():
def __init__(self,host,port,user,pwd,name,charset):
self.host = host
self.port = port
self.user = user
self.pwd = pwd
self.name = name
self.charset = charset
self.sql = ""
self.conn = none
def connectsql(self):
#鏈結資料庫
try:
self.conn = pymysql.connect(self.host, user=self.user, passwd=self.pwd, db=self.name)
cursor = self.conn.cursor()
print("資料庫鏈結成功")
return cursor
except pymysql.error as e:
print(e)
def get_one(self,sql):
#獲取符合sql語句中的第一條
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchone()
except pymysql.error as e:
print(e)
def get_all(self,sql):
#獲取符合sql語句的所有資料
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchall()
except pymysql.error as e:
print(e)
def get_many(self,sql,n):
#獲取符合sql語句中的部分
try:
cur = self.connectsql()
cur.execute(sql)
return cur.fetchmany(n)
except pymysql.error as e:
print(e)
def update(self,sql):
#更新資料庫操作
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.error as e :
print(e)
def alert_add(self,sql):
#增加一列
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.error as e:
print(e)
def alert_modify(self,sql):
#更改一列的資料型別
try:
cur = self.connectsql()
num = cur.execute(sql)
self.conn.commit()
return num
except pymysql.error as e:
print(e)
if __name__ == '__main__':
host = "127.0.0.1"
port = "3306"
user = "root"
pwd = "dy******5"
name = "django_demo"
charset = "utf-8"
sql1 = "select * from booktest_heroinfo;"
sql = "update booktest_heroinfo set actor_content='打大美女' where id=2;"
sql2 = "alter table booktest_heroinfo add column actor_tv varchar(20);"
sql3 = "alter table date_test modify sid varchar(30);"
cursor = dbfunc(host,port,user,pwd,name,charset)
# print(cursor.get_one(sql))
# print(cursor.get_all(sql))
# print(cursor.get_many(sql,2))
# print(cursor.update(sql))
# print(cursor.get_all(sql1))
# print(cursor.alert_add(sql2))
print(cursor.alert_modify(sql3))
python運算元據庫
資料庫的操作在現在的python裡面已經變得十分的好用,有了一套api標準.下面的就是講講如何的去使用這套框架定義.此框架包含以下部分 connect parameters.其中的引數格式如下 dsn 資料來源名稱 user 使用者名稱 可選 password 密碼 可選 host 主機名 可選 d...
python 運算元據庫
目的 通過excel定義檢查指標項,然後通過python讀取指標,通過oracle sqlplus工具去執行獲取具體巡檢結果。unicode utf 8 coding utf 8 import os import sys import xlrd import paramiko reload sys ...
python運算元據庫
python運算元據庫都是通過資料庫驅動取操作的。現在主要有兩張,一種是通過pymysql,還有一種是通過sqlalchemy。在這裡可能還會有人說還有mysqldb模組也可以操作。確實是的,但是mysqldb對python3已經不支援了,所以這裡我就不討論了。第一種pymysql pymysql幫...