Python資料庫操作

2021-09-18 06:19:41 字數 3099 閱讀 2306

獲得當前工作目錄

import os

current_folder=os.getcwd()

生成資料庫檔案路徑

path=current_folder+'\output\test.mdb'
資料庫連線

def __init__(self,path):

self.conn = pyodbc.connect(r"driver=;dbq=" + path + ";uid=;pwd=;")

self.cursor = self.conn.cursor()

執行sql語句

def run_sql(self,sql):

self.cursor.execute(sql)

退出程式

def close(self):

#提交所有執行語句

self.conn.commit()

self.cursor.close()

self.conn.close()

建立**

def create_table(self,name,key):

sql="create table "+name+"("+key+")"

self.run_sql(sql)

複製**

def coppy_table(self,copy_table,new_table):

sql="select * into "+new_table+" from "+copy_table+" where 1<>1"

self.run_sql(sql)

刪除**

def drop_table(self,name):

sql="drop table "+name

self.run_sql(sql)

獲取**列首

def get_table_column(self,table):

colunm_list=

backdata=self.cursor.columns(table)

for row in backdata:

return colunm_list

查詢資料

def select(self,table_name,key,codition):

sql="select "+key+" from "+table_name+" where "+ codition

self.cursor.execute(sql)

backdata=self.cursor.fetchall()

return backdata

插入資料

def insert(self,table_name,column_list,value_list):

colunm_name_str='('

value_str='('

for index in range(0,len(column_list)):

colunm_name_str=colunm_name_str+column_list[index]+','

value_str=value_str+'\''+str(value_list[index])+'\','

colunm_name_str=colunm_name_str[:-1]+')'

value_str=value_str[:-1]+')'

sql='insert into %s %s values %s'%(table_name,colunm_name_str,value_str)

self.run_sql(sql)

1. connection 物件方法

close():關閉資料庫 

commit():提交當前事務 

rollback():取消當前事務 

cursor():獲取當前連線的游標 

errorhandler()作為已給游標的控制代碼 

2. cursor游標物件和方法

arrysize(): 使用fetchmany()方法時一次取出的記錄數,預設為1 

connection():建立此游標的連線 

discription():返回游標的活動狀態,包括(7要素)(name,type_code,display_size,internal_size,precision,scale,null_ok)其中name,type_code是必須的 

lastrowid():返回最後更新行的id,如果資料庫不支援,返回none. 

rowcount():最後一次execute()返回或者影響的行數 

callproc():呼叫乙個儲存過程 

close():關閉游標 

execute():執行sql語句或者資料庫命令 

executemany():一次執行多條sql語句 

fetchone():匹配結果的下一行 

fetchall():匹配所有剩餘結果 

fetchmany(size-cursor,arraysize):匹配結果的下幾行 

iter():建立迭代物件(可選,參考next()) 

messages():游標執行好資料庫返回的資訊列表(元組集合) 

next():使用迭代物件得到結果的下一行 

nextset():移動到下乙個結果集 

rownumber():當前結果集中游標的索引(從0行開始) 

setinput-size(sizes):設定輸入的最大值 

setoutput-size(sizes[,col]):設定列輸出的緩衝值

python 資料庫操作

例子1 建立乙個資料庫 coding utf 8 中文注釋 import mysqldb 建立和資料庫系統的連線 conn mysqldb.connect host localhost user root passwd 獲取操作游標 cursor conn.cursor 執行sql,建立乙個資料庫 ...

Python資料庫操作

我們之前接觸過的儲存資料的方式都是 1.字串 2.列表 3.元組 4.字典 以上方式其實是屬於同一種方式,即將資料儲存在記憶體中 實際在開發過程中,資料儲存主要有三種形式 1.將資料儲存到記憶體中 優點 使用方便,讀寫速度快 缺點 程式關閉的時候,記憶體會釋放,資料會消失 2.將資料寫入到檔案中 優...

Python資料庫操作

定義 資料庫是儲存資料的倉庫,按照一定的資料模型進行組織 描述和儲存。可以以最大的程度減少冗餘度。資料庫管理系統的分類 常用的資料庫模型 支援的型別 null integer real text blob py對應的型別 none int float str bytes sqlite3模組 該模組定...