python資料庫查詢語句
『壹』 python使用oracle查詢資料庫,查詢語句中使用變數值
cursor.execute('select * from INV.MTL_ITEM_REVISIONS where ROW_ID= %s'% (Item,))
換為:
qry_sql = "select * from INV.MTL_ITEM_REVISIONS where ROW_ID= '%s'" % Item
cursor.execute(qry_sql)
『貳』 python對資料庫表格裡面的內容增刪查改怎麼寫
本文主要給大家介紹了關於python模擬sql語句對員工表格進行增刪改查的相關內容,分享出來供大家參考學習,下面來一起看看詳細的介紹:
具體需求:
員工信息表程序,實現增刪改查操作:
可進行模糊查詢,語法支持下面3種:
select name,age from staff_data where age > 22 多個查詢參數name,age 用','分割
select * from staff_data where dept = 人事
select * from staff_data where enroll_date like 2013
查到的信息,列印後,最後面還要顯示查到的條數
可創建新員工紀錄,以phone做唯一鍵,phone存在即提示,staff_id需自增,添加多個記錄record1/record2中間用'/'分割
insert into staff_data values record1/record2
可刪除指定員工信息紀錄,輸入員工id,即可刪除
delete from staff_data where staff_id>=5andstaff_id<=10
可修改員工信息,語法如下:
update staff_table set dept=Market,phone=13566677787 where dept = 運維 多個set值用','分割
使用re模塊,os模塊,充分使用函數精簡代碼,熟練使用 str.split()來解析格式化字元串
由於,sql命令中的幾個關鍵字元串有一定規律,只出現一次,並且有順序!!!
按照key_lis = ['select', 'insert', 'delete', 'update', 'from', 'into', 'set', 'values', 'where', 'limit']的元素順序分割sql.
分割元素作為sql_dic字典的key放進字典中.分割後的列表為b,如果len(b)>1,說明sql字元串中含有分割元素,同時b[0]對應上一個分割元素的值,b[-1]為下一次分割對象!
這樣不斷迭代直到把sql按出現的所有分割元素分割完畢,但注意這里每次循環都是先分割後賦值!!!當前分割元素比如'select'對應的值,需要等到下一個分割元素
比如'from'執行分割後的列表b,其中b[0]的值才會賦值給sql_dic['select'] ,所以最後一個分割元素的值,不能通過上述循環來完成,必須先處理可能是最後一個分割元素,再正常循環!!
在這sql語句中,有可能成為最後一個分割元素的 'limit' ,'values', 'where', 按優先順序別,先處理'limit' ,再處理'values'或 'where'.....
處理完得到sql_dic後,就是你按不同命令執行,對數據文件的增刪改查,最後返回處理結果!!
示例代碼# _*_coding:utf-8_*_# Author:Jaye Heimport reimport os def sql_parse(sql, key_lis): ''' 解析sql命令字元串,按照key_lis列表裡的元素分割sql得到字典形式的命令sql_dic :param sql: :param key_lis: :return: ''' sql_list = [] sql_dic = {} for i in key_lis: b = [j.strip() for j in sql.split(i)] if len(b) > 1: if len(sql.split('limit')) > 1: sql_dic['limit'] = sql.split('limit')[-1] if i == 'where' or i == 'values': sql_dic[i] = b[-1] if sql_list: sql_dic[sql_list[-1]] = b[0] sql_list.append(i) sql = b[-1] else: sql = b[0] if sql_dic.get('select'): if not sql_dic.get('from') and not sql_dic.get('where'): sql_dic['from'] = b[-1] if sql_dic.get('select'): sql_dic['select'] = sql_dic.get('select').split(',') if sql_dic.get('where'): sql_dic['where'] = where_parse(sql_dic.get('where')) return sql_dic def where_parse(where): ''' 格式化where字元串為列表where_list,用'and', 'or', 'not'分割字元串 :param where: :return: ''' casual_l = [where] logic_key = ['and', 'or', 'not'] for j in logic_key: for i in casual_l: if i not in logic_key: if len(i.split(j)) > 1: ele = i.split(j) index = casual_l.index(i) casual_l.pop(index) casual_l.insert(index, ele[0]) casual_l.insert(index+1, j) casual_l.insert(index+2, ele[1]) casual_l = [k for k in casual_l if k] where_list = three_parse(casual_l, logic_key) return where_list def three_parse(casual_l, logic_key): ''' 處理臨時列表casual_l中具體的條件,'staff_id>5'-->['staff_id','>','5'] :param casual_l: :param logic_key: :return: ''' where_list = [] for i in casual_l: if i not in logic_key: b = i.split('like') if len(b) > 1: b.insert(1, 'like') where_list.append(b) else: key = ['<', '=', '>'] new_lis = [] opt = '' lis = [j for j in re.split('([=<>])', i) if j] for k in lis: if k in key: opt += k else: new_lis.append(k) new_lis.insert(1, opt) where_list.append(new_lis) else: where_list.append(i) return where_list def sql_action(sql_dic, title): ''' 把解析好的sql_dic分發給相應函數執行處理 :param sql_dic: :param title: :return: ''' key = {'select': select, 'insert': insert, 'delete': delete, 'update': update} res = [] for i in sql_dic: if i in key: res = key[i](sql_dic, title) return res def select(sql_dic, title): ''' 處理select語句命令 :param sql_dic: :param title: :return: ''' with open('staff_data', 'r', encoding='utf-8') as fh: filter_res = where_action(fh, sql_dic.get('where'), title) limit_res = limit_action(filter_res, sql_dic.get('limit')) search_res = search_action(limit_res, sql_dic.get('select'), title) return search_res def insert(sql_dic, title): ''' 處理insert語句命令 :param sql_dic: :param title: :return: ''' with open('staff_data', 'r+', encoding='utf-8') as f: data = f.readlines() phone_list = [i.strip().split(',')[4] for i in data] ins_count = 0 if not data: new_id = 1 else: last = data[-1] last_id = int(last.split(',')[0]) new_id = last_id+1 record = sql_dic.get('values').split('/') for i in record: if i.split(',')[3] in phone_list: print('\033[1;31m%s 手機號已存在\033[0m' % i) else: new_record = '%s,%s\n' % (str(new_id), i) f.write(new_record) new_id += 1 ins_count += 1 f.flush() return ['insert successful'], [str(ins_count)] def delete(sql_dic, title): ''' 處理delete語句命令 :param sql_dic: :param title: :return: ''' with open('staff_data', 'r', encoding='utf-8') as r_file,\ open('staff_data_bak', 'w', encoding='utf-8') as w_file: del_count = 0 for line in r_file: dic = dict(zip(title.split(','), line.split(','))) filter_res = logic_action(dic, sql_dic.get('where')) if not filter_res: w_file.write(line) else: del_count += 1 w_file.flush() os.remove('staff_data') os.rename('staff_data_bak', 'staff_data') return ['delete successful'], [str(del_count)] def update(sql_dic, title): ''' 處理update語句命令 :param sql_dic: :param title: :return: ''' set_l = sql_dic.get('set').strip().split(',') set_list = [i.split('=') for i in set_l] update_count = 0 with open('staff_data', 'r', encoding='utf-8') as r_file,\ open('staff_data_bak', 'w', encoding='utf-8') as w_file: for line in r_file: dic = dict(zip(title.split(','), line.strip().split(','))) filter_res = logic_action(dic, sql_dic.get('where')) if filter_res: for i in set_list: k = i[0] v = i[-1] dic[k] = v line = [dic[i] for i in title.split(',')] update_count += 1 line = ','.join(line)+'\n' w_file.write(line) w_file.flush() os.remove('staff_data') os.rename('staff_data_bak', 'staff_data') return ['update successful'], [str(update_count)] def where_action(fh, where_list, title): ''' 具體處理where_list里的所有條件 :param fh: :param where_list: :param title: :return: ''' res = [] if len(where_list) != 0: for line in fh: dic = dict(zip(title.split(','), line.strip().split(','))) if dic['name'] != 'name': logic_res = logic_action(dic, where_list) if logic_res: res.append(line.strip().split(',')) else: res = [i.split(',') for i in fh.readlines()] return res pass def logic_action(dic, where_list): ''' 判斷數據文件中每一條是否符合where_list條件 :param dic: :param where_list: :return: ''' logic = [] for exp in where_list: if type(exp) is list: exp_k, opt, exp_v = exp if exp[1] == '=': opt = '==' logical_char = "'%s'%s'%s'" % (dic[exp_k], opt, exp_v) if opt != 'like': exp = str(eval(logical_char)) else: if exp_v in dic[exp_k]: exp = 'True' else: exp = 'False' logic.append(exp) res = eval(' '.join(logic)) return res def limit_action(filter_res, limit_l): ''' 用列表切分處理顯示符合條件的數量 :param filter_res: :param limit_l: :return: ''' if limit_l: index = int(limit_l[0]) res = filter_res[:index] else: res = filter_res return res def search_action(limit_res, select_list, title): ''' 處理需要查詢並顯示的title和相應數據 :param limit_res: :param select_list: :param title: :return: ''' res = [] fields_list = title.split(',') if select_list[0] == '*': res = limit_res else: fields_list = select_list for data in limit_res: dic = dict(zip(title.split(','), data)) r_l = [] for i in fields_list: r_l.append((dic[i].strip())) res.append(r_l) return fields_list, res if __name__ == '__main__': with open('staff_data', 'r', encoding='utf-8') as f: title = f.readline().strip() key_lis = ['select', 'insert', 'delete', 'update', 'from', 'into', 'set', 'values', 'where', 'limit'] while True: sql = input('請輸入sql命令,退出請輸入exit:').strip() sql = re.sub(' ', '', sql) if len(sql) == 0:continue if sql == 'exit':break sql_dict = sql_parse(sql, key_lis) fields_list, fields_data = sql_action(sql_dict, title) print('\033[1;33m結果如下:\033[0m') print('-'.join(fields_list)) for data in fields_data: print('-'.join(data))
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
『叄』 如何用python寫sql
python可以利用pymysql模塊操作資料庫。
什麼是 PyMySQL?
PyMySQL 是在 Python3.x 版本中用於連接 MySQL 伺服器的一個庫,Python2中則使用mysqldb。
PyMySQL 遵循 Python 資料庫 API v2.0 規范,並包含了 pure-Python MySQL 客戶端庫。
PyMySQL 安裝
在使用 PyMySQL 之前,我們需要確保 PyMySQL 已安裝。
PyMySQL 下載地址:https://github.com/PyMySQL/PyMySQL。
如果還未安裝,我們可以使用以下命令安裝最新版的 PyMySQL:
$ pip3 install PyMySQL
如果你的系統不支持 pip 命令,可以使用以下方式安裝:
1、使用 git 命令下載安裝包安裝(你也可以手動下載):
$ git clone https://github.com/PyMySQL/PyMySQL$ cd PyMySQL/$ python3 setup.py install
2、如果需要制定版本號,可以使用 curl 命令來安裝:
$ # X.X 為 PyMySQL 的版本號$ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz$ cd PyMySQL*$ python3 setup.py install
$ # 現在你可以刪除 PyMySQL* 目錄
注意:請確保您有root許可權來安裝上述模塊。
安裝的過程中可能會出現"ImportError: No mole named setuptools"的錯誤提示,意思是你沒有安裝setuptools,你可以訪問https://pypi.python.org/pypi/setuptools找到各個系統的安裝方法。
Linux 系統安裝實例:
$ wget https://bootstrap.pypa.io/ez_setup.py$ python3 ez_setup.py
資料庫連接
連接資料庫前,請先確認以下事項:
您已經創建了資料庫 TESTDB.
在TESTDB資料庫中您已經創建了表 EMPLOYEE
EMPLOYEE表欄位為 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。
連接資料庫TESTDB使用的用戶名為 "testuser" ,密碼為 "test123",你可以可以自己設定或者直接使用root用戶名及其密碼,Mysql資料庫用戶授權請使用Grant命令。
在你的機子上已經安裝了 Python MySQLdb 模塊。
如果您對sql語句不熟悉,可以訪問我們的SQL基礎教程
- Database version : 5.5.20-log
- ..................................user_id = "test123"password = "password"con.execute('insert into Login values( %s, %s)' % (user_id, password))..................................
fetchone():該方法獲取下一個查詢結果集。結果集是一個對象
fetchall():接收全部的返回結果行.
rowcount:這是一個只讀屬性,並返回執行execute()方法後影響的行數。
- fname=Mac, lname=Mohan, age=20, sex=M, income=2000
原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。
一致性(consistency)。事務必須是使資料庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。
隔離性(isolation)。一個事務的執行不能被其他事務干擾。即一個事務內部的操作及使用的數據對並發的其他事務是隔離的,並發執行的各個事務之間不能互相干擾。
持久性(rability)。持續性也稱永久性(permanence),指一個事務一旦提交,它對資料庫中數據的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
實例:
以下實例鏈接 Mysql 的 TESTDB 資料庫:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用 cursor() 方法創建一個游標對象 cursorcursor = db.cursor()
# 使用 execute() 方法執行 SQL 查詢 cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條數據.data = cursor.fetchone()
print ("Database version : %s " % data)
# 關閉資料庫連接db.close()
執行以上腳本輸出結果如下:
創建資料庫表
如果資料庫連接存在我們可以使用execute()方法來為資料庫創建表,如下所示創建表EMPLOYEE:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用 cursor() 方法創建一個游標對象 cursorcursor = db.cursor()
# 使用 execute() 方法執行 SQL,如果表存在則刪除cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用預處理語句創建表sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# 關閉資料庫連接db.close()
資料庫插入操作
以下實例使用執行 SQL INSERT 語句向表 EMPLOYEE 插入記錄:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標 cursor = db.cursor()
# SQL 插入語句sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""try: # 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()except: # 如果發生錯誤則回滾
db.rollback()
# 關閉資料庫連接db.close()
以上例子也可以寫成如下形式:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標 cursor = db.cursor()
# SQL 插入語句sql = "INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('%s', '%s', %s, '%s', %s)" % ('Mac', 'Mohan', 20, 'M', 2000)try: # 執行sql語句
cursor.execute(sql)
# 執行sql語句
db.commit()except: # 發生錯誤時回滾
db.rollback()
# 關閉資料庫連接db.close()
以下代碼使用變數向SQL語句中傳遞參數:
資料庫查詢操作
Python查詢Mysql使用 fetchone() 方法獲取單條數據, 使用fetchall() 方法獲取多條數據。
實例:
查詢EMPLOYEE表中salary(工資)欄位大於1000的所有數據:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標 cursor = db.cursor()
# SQL 查詢語句sql = "SELECT * FROM EMPLOYEE
WHERE INCOME > %s" % (1000)try: # 執行SQL語句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results: fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 列印結果
print ("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % (fname, lname, age, sex, income ))except: print ("Error: unable to fetch data")
# 關閉資料庫連接db.close()
以上腳本執行結果如下:
資料庫更新操作
更新操作用於更新數據表的的數據,以下實例將 TESTDB 表中 SEX 為 'M' 的 AGE 欄位遞增 1:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標 cursor = db.cursor()
# SQL 更新語句sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')try: # 執行SQL語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()except: # 發生錯誤時回滾
db.rollback()
# 關閉資料庫連接db.close()
刪除操作
刪除操作用於刪除數據表中的數據,以下實例演示了刪除數據表 EMPLOYEE 中 AGE 大於 20 的所有數據:
實例(Python 3.0+)
#!/usr/bin/python3
import pymysql
# 打開資料庫連接db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標 cursor = db.cursor()
# SQL 刪除語句sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)try: # 執行SQL語句
cursor.execute(sql)
# 提交修改
db.commit()except: # 發生錯誤時回滾
db.rollback()
# 關閉連接db.close()
執行事務
事務機制可以確保數據一致性。
事務應該具有4個屬性:原子性、一致性、隔離性、持久性。這四個屬性通常稱為ACID特性。
Python DB API 2.0 的事務提供了兩個方法 commit 或 rollback。
實例
實例(Python 3.0+)
# SQL刪除記錄語句sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % (20)try: # 執行SQL語句
cursor.execute(sql)
# 向資料庫提交
db.commit()except: # 發生錯誤時回滾
db.rollback()
對於支持事務的資料庫, 在Python資料庫編程中,當游標建立之時,就自動開始了一個隱形的資料庫事務。
commit()方法游標的所有更新操作,rollback()方法回滾當前游標的所有操作。每一個方法都開始了一個新的事務。
錯誤處理
DB API中定義了一些資料庫操作的錯誤及異常,下表列出了這些錯誤和異常:
異常
描述
Warning 當有嚴重警告時觸發,例如插入數據是被截斷等等。必須是 StandardError 的子類。
Error 警告以外所有其他錯誤類。必須是 StandardError 的子類。
InterfaceError 當有資料庫介面模塊本身的錯誤(而不是資料庫的錯誤)發生時觸發。 必須是Error的子類。
DatabaseError 和資料庫有關的錯誤發生時觸發。 必須是Error的子類。
DataError 當有數據處理時的錯誤發生時觸發,例如:除零錯誤,數據超范圍等等。 必須是DatabaseError的子類。
OperationalError 指非用戶控制的,而是操作資料庫時發生的錯誤。例如:連接意外斷開、 資料庫名未找到、事務處理失敗、內存分配錯誤等等操作資料庫是發生的錯誤。 必須是DatabaseError的子類。
IntegrityError 完整性相關的錯誤,例如外鍵檢查失敗等。必須是DatabaseError子類。
InternalError 資料庫的內部錯誤,例如游標(cursor)失效了、事務同步失敗等等。 必須是DatabaseError子類。
ProgrammingError 程序錯誤,例如數據表(table)沒找到或已存在、SQL語句語法錯誤、 參數數量錯誤等等。必須是DatabaseError的子類。
NotSupportedError 不支持錯誤,指使用了資料庫不支持的函數或API等。例如在連接對象上 使用.rollback()函數,然而資料庫並不支持事務或者事務已關閉。 必須是DatabaseError的子類。
『肆』 python資料庫怎麼查詢數據
Python通過pymysql連接資料庫並進行查詢和更新SQL方法封裝
import pymysql.cursors
import json
class OperationMysql:
def __init__(self):
self.conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='test',
passwd='11111',
db='test',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor
)
self.cur = self.conn.cursor()
# 查詢一條數據
def search_one(self, sql):
self.cur.execute(sql)
result = self.cur.fetchone()
return result
# 更新SQL
def updata_one(self, sql):
self.cur.execute(sql)
self.conn.commit()
self.conn.close()
if __name__ == '__main__':
op_mysql = OperationMysql()
res = op_mysql.search_one("SELECT * from order WHERE order_no='M191023401681654'")
print(res)
『伍』 python 怎麼查詢mysql資料庫
#!/usr/bin/python
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
#打開游標
cursor = db.cursor()
# 執行資料庫查詢
cursor.execute("SELECT * from users")
# 獲取結果集的第一行
data = cursor.fetchone()
print "Database version : %s " % data
# 關閉連接
db.close()
『陸』 如何使用python連接資料庫,插入並查詢數據
你可以訪問Python資料庫介面及API查看詳細的支持資料庫列表。不同的資料庫你需要下載不同的DB API模塊,例如你需要訪問Oracle資料庫和Mysql數據,你需要下載Oracle和MySQL資料庫模塊。
DB-API 是一個規范. 它定義了一系列必須的對象和資料庫存取方式, 以便為各種各樣的底層資料庫系統和多種多樣的資料庫介面程序提供一致的訪問介面 。
Python的DB-API,為大多數的資料庫實現了介面,使用它連接各資料庫後,就可以用相同的方式操作各資料庫。
Python DB-API使用流程:
引入 API 模塊。
獲取與資料庫的連接。
執行SQL語句和存儲過程。
關閉資料庫連接。
什麼是MySQLdb?
MySQLdb 是用於Python鏈接Mysql資料庫的介面,它實現了 Python 資料庫 API 規范 V2.0,基於 MySQL C API 上建立的。
如何安裝MySQLdb?
為了用DB-API編寫MySQL腳本,必須確保已經安裝了MySQL。復制以下代碼,並執行:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
如果執行後的輸出結果如下所示,意味著你沒有安裝 MySQLdb 模塊:
Traceback (most recent call last):
File "test.py", line 3, in <mole>
import MySQLdb
ImportError: No mole named MySQLdb
安裝MySQLdb,請訪問 ,(Linux平台可以訪問:)從這里可選擇適合您的平台的安裝包,分為預編譯的二進制文件和源代碼安裝包。
如果您選擇二進制文件發行版本的話,安裝過程基本安裝提示即可完成。如果從源代碼進行安裝的話,則需要切換到MySQLdb發行版本的頂級目錄,並鍵入下列命令:
$ gunzip MySQL-python-1.2.2.tar.gz
$ tar -xvf MySQL-python-1.2.2.tar
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install
注意:請確保您有root許可權來安裝上述模塊。
資料庫連接
連接資料庫前,請先確認以下事項:
您已經創建了資料庫 TESTDB.
在TESTDB資料庫中您已經創建了表 EMPLOYEE
EMPLOYEE表欄位為 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。
連接資料庫TESTDB使用的用戶名為 "testuser" ,密碼為 "test123",你可以可以自己設定或者直接使用root用戶名及其密碼,Mysql資料庫用戶授權請使用Grant命令。
在你的機子上已經安裝了 Python MySQLdb 模塊。
如果您對sql語句不熟悉,可以訪問我們的 SQL基礎教程
實例:
以下實例鏈接Mysql的TESTDB資料庫:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# 使用execute方法執行SQL語句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取一條資料庫。
data = cursor.fetchone()
print "Database version : %s " % data
# 關閉資料庫連接
db.close()
執行以上腳本輸出結果如下:
Database version : 5.0.45
創建資料庫表
如果資料庫連接存在我們可以使用execute()方法來為資料庫創建表,如下所示創建表EMPLOYEE:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# 如果數據表已經存在使用 execute() 方法刪除表。
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 創建數據表SQL語句
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# 關閉資料庫連接
db.close()
資料庫插入操作
以下實例使用執行 SQL INSERT 語句向表 EMPLOYEE 插入記錄:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 插入語句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# 關閉資料庫連接
db.close()
以上例子也可以寫成如下形式:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 插入語句
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# 執行sql語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉資料庫連接
db.close()
實例:
以下代碼使用變數向SQL語句中傳遞參數:
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
(user_id, password))
..................................
資料庫查詢操作
Python查詢Mysql使用 fetchone() 方法獲取單條數據, 使用fetchall() 方法獲取多條數據。
fetchone(): 該方法獲取下一個查詢結果集。結果集是一個對象
fetchall():接收全部的返回結果行.
rowcount: 這是一個只讀屬性,並返回執行execute()方法後影響的行數。
實例:
查詢EMPLOYEE表中salary(工資)欄位大於1000的所有數據:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# 執行SQL語句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 列印結果
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"
# 關閉資料庫連接
db.close()
以上腳本執行結果如下:
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
資料庫更新操作
更新操作用於更新數據表的的數據,以下實例將 TESTDB表中的 SEX 欄位全部修改為 'M',AGE 欄位遞增1:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 更新語句
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# 執行SQL語句
cursor.execute(sql)
# 提交到資料庫執行
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉資料庫連接
db.close()
刪除操作
刪除操作用於刪除數據表中的數據,以下實例演示了刪除數據表 EMPLOYEE 中 AGE 大於 20 的所有數據:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
# 打開資料庫連接
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 刪除語句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# 執行SQL語句
cursor.execute(sql)
# 提交修改
db.commit()
except:
# 發生錯誤時回滾
db.rollback()
# 關閉連接
db.close()
執行事務
事務機制可以確保數據一致性。
事務應該具有4個屬性:原子性、一致性、隔離性、持久性。這四個屬性通常稱為ACID特性。
原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要麼都做,要麼都不做。
一致性(consistency)。事務必須是使資料庫從一個一致性狀態變到另一個一致性狀態。一致性與原子性是密切相關的。
隔離性(isolation)。一個事務的執行不能被其他事務干擾。即一個事務內部的操作及使用的數據對並發的其他事務是隔離的,並發執行的各個事務之間不能互相干擾。
持久性(rability)。持續性也稱永久性(permanence),指一個事務一旦提交,它對資料庫中數據的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
Python DB API 2.0 的事務提供了兩個方法 commit 或 rollback。
『柒』 python使用資料庫
增加一條數據
importpymysql
#返回Connection對象
#host="localhost"
con=pymysql.connect(host="192.168.31.28",
port=3306,user="atguigu",
password="atguigu",
db="atguigudb",
charset="utf8")
#返回cursor對象
cursor=con.cursor()
#SQL語言-SQL語句
sql="insertintostudents(name)value('李四')"
#插入數據
cursor.execute(sql)
#提交數據,沒有提交就沒有數據
con.commit()
#關閉釋放資源
cursor.close()
#關閉資源
con.close()
修改數據
importpymysql
#修改任意一條數據
#返回Connection對象
conn=pymysql.connect(
host="192.168.31.28",
db="atguigudb",
port=3306,
user="atguigu",
password="atguigu",
charset="utf8"
)
cursor=conn.cursor()
sql="updatestudentssetname='郭靖'whereid=1"
count=cursor.execute(sql)
print("count=",count)
#提交正常數據物理上修改了
conn.commit()
cursor.close()
conn.close()
刪除數據
importpymysql
#修改任意一條數據
#返回Connection對象
conn=pymysql.connect(
host="192.168.31.28",
db="atguigudb",
port=3306,
user="atguigu",
password="atguigu",
charset="utf8"
)
cursor=conn.cursor()
sql="deletefromstudentswhereid=20"
count=cursor.execute(sql)
print("count=",count)
conn.commit()
cursor.close()
conn.close()
查詢一條數據
importpymysql
try:
conn=pymysql.connect(
host='192.168.31.28',
port=3306,
db='atguigudb',
user='atguigu',
passwd='atguigu',
charset='utf8'
)
cursor=conn.cursor()
cursor.execute('select*fromstudentswhereid=3')
#返回滿足這個條件的這個數據,如果有多條返回第一條,並且封裝元組中
result=cursor.fetchone()
print(result)
foriinresult:
print(i)
cursor.close()
conn.close()
exceptExceptionase:
print(e.message)
查詢多條數據
importpymysql
try:
conn=pymysql.connect(
host='192.168.31.28',
port=3306,
db='atguigudb',
user='atguigu',
passwd='atguigu',
charset='utf8'
)
cursor=conn.cursor()
cursor.execute('select*fromstudents')
#返回元組,如果多條數據,元組裡面嵌套元組
result=cursor.fetchall()
print(result)
foriinresult:
print(i)
conn.commit()
cursor.close()
conn.close()
exceptExceptionase:
print(e.message)
讀取mysql數據,填寫數據到excel
frompyexcel_xlsimportsave_data
frompyexcel_xlsimportget_data
importmysql.connector
#和資料庫建立連接
cnx=mysql.connector.connect(user='root',password='',
host='127.0.0.1',
database='test')
#查詢語句
sql="selectmy_name,my_valuefromtbl_members"
#執行查詢
cursor.execute(sql)
#獲得查詢結果
result=cursor.fetchall()
cursor.close()
cnx.close()
#打開預定義表頭文件
xls_header=get_data("d:/xh.xls")
#獲得表頭數據
xh=xls_header.pop("Sheet1")
#拼接整表數據
xd=OrderedDict()
xd.update({"Sheet1":xh+result})
#保存到另一個文件中
save_data("d:/xd.xls",xd)
『捌』 如何用python pymysql查看資料庫
1、python安裝目錄設定為d:/python342、pymysql安裝方法為:解壓下載的文件,在cmd中運行: python setup.py install。
檢驗安裝安裝是否成功的方法:import pymysql 。 如果不報錯 說明安裝成功。
3、mysql安裝目錄為D:/phpStudy/MySQL。為避免更多配置問題,可在啟動phpstudy後,將其設為系統服務
4、基本操作:
(1)導入pymysql: import pymysql
(2)連接資料庫:
conn=pymysql.connect(host='localhost',user='root',passwd='root',db='ere',charset='utf8')
務必注意各等號前面的內容!charset參數可避免中文亂碼
(3)獲取操作游標:cur=conn.cursor()
(4)執行sql語句,插入記錄:sta=cur.execute("insert 語句") 執行成功後sta值為1。更新、刪除語句與此類似。
(5)執行sql語句,查詢記錄:cur.execute("select語句") 執行成功後cur變數中保存了查詢結果記錄集,然後再用循環列印結果:
for each in cur:
print(each[1].decode('utf-8')) # each[1] 表示當前游標所在行的的第2列值,如果是中文則需要處理編碼
『玖』 python中連接資料庫成功後怎樣將SQL查詢語句結果取回作數據分析
一般是cursor.fetchall() 或者cursor.fetchone()
看你是一次性取所有查詢結果還是一條一條取
『拾』 Python資料庫API(DB API)
雖然 Python 需要為操作不同的資料庫使用不同的模塊,但不同的資料庫模塊並非沒有規律可循,因為它們基本都遵守 Python 制訂的 DB API 協議,目前該協議的最新版本是 2.0,因此這些資料庫模塊有很多操作其實都是相同的。下面先介紹不同資料庫模塊之間的通用內容。
全局變數
Python 推薦支持 DB API 2.0 的資料庫模塊都應該提供如下 3 個全局變數:
apilevel:該全局變數顯示資料庫模塊的 API 版本號。對於支持 DB API 2.0 版本的資料庫模塊來說,該變數值通常就是 2.0。如果這個變數不存在,則可能該資料庫模塊暫時不支持 DB API 2.0。讀者應該考慮選擇使用支持該資料庫的其他資料庫模塊。
threadsafety:該全局變數指定資料庫模塊的線程安全等級,該等級值為 0~3 ,其中 3 代表該模塊完全是線程安全的;1 表示該模塊具有部分線程安全性,線程可以共享該模塊,但不能共享連接;0 則表示線程完全不能共享該模塊。
paramstyle:該全局變數指定當 SQL 語句需要參數時,可以使用哪種風格的參數。該變數可能返回如下變數值:
format:表示在 SQL 語句中使用 Python 標準的格式化字元串代表參數。例如,在程序中需要參數的地方使用 %s,接下來程序即可為這些參數指定參數值。
pyformat:表示在 SQL 語句中使用擴展的格式代碼代表參數。比如使用 %(name),這樣即可使用包含 key 為 name 的字典為該參數指定參數值。
qmark:表示在 SQL 語句中使用問號(?)代表參數。在 SQL 語句中有幾個參數,全部用問號代替。
numeric:表示在 SQL 語句中使用數字佔位符(:N)代表參數。例如:1 代表一個參數,:2 也表示一個參數,這些數字相當於參數名,因此它們不一定需要連續。
named:表示在 SQL 語句中使用命名佔位符(:name)代表參數。例如 :name 代表一個參數,:age 也表示一個參數。
通過查閱這些全局變數,即可大致了解該資料庫 API 模塊的對外的編程風格,至於該模塊內部的實現細節,完全由該模塊實現者負責提供,通常不需要開發者關心。
資料庫 API 的核心類
遵守 DB API 2.0 協議的資料庫模塊通常會提供一個 connect() 函數,該函數用於連接資料庫,並返回資料庫連接對象。
資料庫連接對象通常會具有如下方法和屬性:
cursor(factory=Cursor):打開游標。
commit():提交事務。
rollback():回滾事務。
close():關閉資料庫連接。
isolation_level:返回或設置資料庫連接中事務的隔離級別。
in_transaction:判斷當前是否處於事務中。
上面第一個方法可以返回一個游標對象,游標對象是 Python DB API 的核心對象,該對象主要用於執行各種 SQL 語句,包括 DDL、DML、select 查詢語句等。使用游標執行不同的 SQL 語句返回不同的數據。
游標對象通常會具有如下方法和屬性:
execute(sql[, parameters]):執行 SQL 語句。parameters 參數用於為 SQL 語句中的參數指定值。
executemany(sql, seq_of_parameters):重復執行 SQL 語句。可以通過 seq_of_parameters 序列為 SQL 語句中的參數指定值,該序列有多少個元素,SQL 語句被執行多少次。
executescript(sql_script):這不是 DB API 2.0 的標准方法。該方法可以直接執行包含多條 SQL 語句的 SQL 腳本。
fetchone():獲取查詢結果集的下一行。如果沒有下一行,則返回 None。
fetchmany(size=cursor.arraysize):返回查詢結果集的下 N 行組成的列表。如果沒有更多的數據行,則返回空列表。
fetchall():返回查詢結果集的全部行組成的列表。
close():關閉游標。
rowcount:該只讀屬性返回受 SQL 語句影響的行數。對於 executemany() 方法,該方法所修改的記錄條數也可通過該屬性獲取。
lastrowid:該只讀屬性可獲取最後修改行的 rowid。
arraysize:用於設置或獲取 fetchmany() 默認獲取的記錄條數,該屬性默認為 1。有些資料庫模塊沒有該屬性。
description:該只讀屬性可獲取最後一次查詢返回的所有列的信息。
connection:該只讀屬性返回創建游標的資料庫連接對象。有些資料庫模塊沒有該屬性。
總結來看,Python 的 DB API 2.0 由一個 connect() 開始,一共涉及資料庫連接和游標兩個核心 API。它們的分工如下:
資料庫連接:用於獲取游標、控制事務。
游標:執行各種 SQL 語句。
掌握了上面這些 API 之後,接下來可以大致歸納出 Python DB API 2.0 的編程步驟。
操作資料庫的基本流程
使用 Python DB API 2.0 操作資料庫的基本流程如下:
調用 connect() 方法打開資料庫連接,該方法返回資料庫連接對象。
通過資料庫連接對象打開游標。
使用游標執行 SQL 語句(包括 DDL、DML、select 查詢語句等)。如果執行的是查詢語句,則處理查詢數據。
關閉游標。
關閉資料庫連接。
下圖顯示了使用 Python DB API 2.0 操作資料庫的基本流程。