當前位置:首頁 » 編程語言 » pythonodbchive

pythonodbchive

發布時間: 2022-04-29 22:21:01

『壹』 如何用python鏈接hive

看你的需求應該是一個python新手,建議你看一下django這個python的web框架,它應該能滿足你的需求,同時也能讓你對python的web開發有一個了解。如果解決了您的問題請採納!如果未解決請繼續追問

『貳』 python 怎麼調用odbc

入門
連接到資料庫
調用connect方法並傳入ODBC連接字元串,其會返回一個connect對象。通過connect對象,調用cursor()方法,可以獲取一個游標cursor。如下代碼示例:
import pyodbc
#連接示例: Windows系統, 非DSN方式, 使用微軟 sql Server 資料庫驅動
cnxn =pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
#連接示例: Linux系統, 非DSN方式, 使用FreeTDS驅動
cnxn =pyodbc.connect('DRIVER={FreeTDS};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass;TDS_Version=7.0')
#連接示例:使用DSN方式
cnxn = pyodbc.connect('DSN=test;PWD=password')
# 打開游標
cursor =cnxn.cursor()
以上示例只是標准示例,具體的ODBC連接字元串以你自己使用的驅動為准。
查詢一些數據
所有SQL語句都使用Cursor.execute()方法執行。比如select語句會返回一些結果行,你可以使用游標(Cursor)相關的函數功能(fetchone,fetchall,fetchmany)對結果進行檢索。
Cursor.fetchone 用於返回一個單行( Row)對象:
cursor.execute("selectuser_id, user_name from users")
row =cursor.fetchone()
if row:
print(row)
Row 對象是類似一個python元組(tuples),不過也可以通過列名稱來訪問,例如:
cursor.execute("selectuser_id, user_name from users")
row =cursor.fetchone()
print('name:',row[1]) # 使用列索引號來訪問數據
print('name:',row.user_name) # 或者直接使用列名來訪問數據
當所有行都已被檢索,則fetchone返回None.
while 1:
row = cursor.fetchone()
if not row:
break
print('id:', row.user_id)
Cursor.fetchall方法返回所有剩餘行並存儲於一個列表中。如果沒有行,則返回一個空列表。(注意:如果有很多行,會造成大量內存佔用。Fetchall會一次性將所有數據查詢到本地,然後再遍歷)
cursor.execute("selectuser_id, user_name from users")
rows = cursor.fetchall()
for row in rows:
print(row.user_id, row.user_name)
如果並不在意數據處理時間,可以使用游標本身作為一個迭代器,逐行迭代。這樣可以節省大量的內存開銷,但是由於和數據來回進行通信,速度會相對較慢:
cursor.execute("selectuser_id, user_name from users"):
for row in cursor:
print(row.user_id, row.user_name)
由於Cursor.execute總是返回遊標(cursor), 所以也可以簡寫成:
for row incursor.execute("select user_id, user_name from users"):
print(row.user_id, row.user_name)
我們可以在execut中使用」」」三重引號,來應用多行SQL字元串。這樣sql的可讀性大大增強。這是python特有的特性:
cursor.execute(
"""
select user_id, user_name
from users
where last_logon < '2001-01-01'
and bill_overe = 1
""")
SQL參數
ODBC支持使用問號作為SQL的查詢參數佔位符。可以在execute方法的SQL參數之後,提供SQL參數佔位符的值:
cursor.execute(
"""
select user_id, user_name
from users
where last_logon < ?
and bill_overe = ?
""", '2001-01-01', 1)
這樣做可以防止SQL注入攻擊,提高安全性。如果使用不同的參數反復執行相同的SQL它效率會更高,這種情況下該SQL將只預裝(prepared )一次。(pyodbc只保留最後一條編寫的語句,所以如果程序在語句之間進行切換,每次都會預裝,造成多次預裝。)
Python的DB API指定參數應以序列(sequence)對象傳遞,所以pyodbc也支持這種方式:
cursor.execute(
"""
select user_id, user_name
from users
where last_logon < ?
and bill_overe = ?
""", ['2001-01-01', 1])
插入數據
插入數據使用相同的函數 - 通過傳入insert SQL和相關佔位參數執行插入數據:
cursor.execute("insertinto procts(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
cursor.execute("insertinto procts(id, name) values (?, ?)", 'pyodbc', 'awesome library')
cnxn.commit()
注意:調用cnxn.commit()。發成錯誤可以回滾。具體需要看資料庫特性支持情況。如果數據發生改變,最好進行commit。如果不提交,則在連接中斷時,所有數據會發生回滾。
更新和刪除數據
更新和刪除工作以同樣的方式:通過特定的SQL來執行。通常我們都想知道更新和刪除的時候有多少條記錄受到影響,可以使用Cursor.rowcount來獲取值:
cursor.execute("deletefrom procts where id <> ?", 'pyodbc')
print('Deleted {}inferior procts'.format(cursor.rowcount))
cnxn.commit()
由於execute 總是返回遊標(允許你調用鏈或迭代器使用),有時我們直接這樣簡寫:
deleted =cursor.execute("delete from procts where id <> 'pyodbc'").rowcount
cnxn.commit()
注意一定要調用commit。否則連接中斷時會造成改動回滾。
技巧和竅門
引號
於單引號SQL是有效的,當值需要使用單引號時,使用用雙引號包圍的SQL:
cursor.execute("deletefrom procts where id <> 'pyodbc'")
如果使用三重引號, 我們可以這樣使用單引號:
cursor.execute(
"""
delete
from procts
where id <> 'pyodbc'
""")
列名稱
Microsoft SQLServer之類的一些資料庫不會產生計算列的列名,在這種情況下,需要通過索引來訪問列。我們也可以使用sql列別名的方式,為計算列指定引用名稱:
row =cursor.execute("select count(*) as user_count fromusers").fetchone()
print('{}users'.format(row.user_count)
當然也可以直接使用列索引來訪問列值:
count =cursor.execute("select count(*) from users").fetchone()[0]
print('{}users'.format(count)
注意,上例的首列不能是Null。否則fetchone方法將返回None並且會報NoneType不支持索引的錯誤。如果有一個默認值,經常可以是ISNULL或合並:
maxid =cursor.execute("select coalesce(max(id), 0) fromusers").fetchone()[0]
自動清理
連接(默認)在一個事務中。如果一個連接關閉前沒有提交,則會進行當前事務回滾。很少需要finally或except 語句來執行人為的清理操作,程序會自動清理。
例如,如果下列執行過程中任何一條SQL語句出現異常,都將引發導致這兩個游標執行失效。從而保證原子性,要麼所有數據都插入發生,要麼所有數據都不插入。不需要人為編寫清理代碼。
cnxn =pyodbc.connect(...)
cursor = cnxn.cursor()
cursor.execute("insertinto t(col) values (1)")
cursor.execute("insertinto t(col) values (2)")
cnxn.commit()

『叄』 hive中如何調用python函數

ADD FILE /home/taobao/dw_hive/hivelets/smoking/ext/tsa/hivesql/bjx_topic_t1/splitsysin.py.bak;
create table if not exists splittest_t1
(
topic_id string,
topic_title string,
topic_desc string,
biz_date string,
gmt_create string
) PARTITIONED BY(pt string)
row format delimited fields terminated by '\001'
lines terminated by '\n'
STORED AS textfile;

select TRANSFORM(topic_id,topic_title,topic_desc,biz_date,gmt_create)
USING 'splitsysin.py'
as topic_id,topic_title,topic_desc,biz_date,gmt_create
from r_bjx_dim_topic_t1;

『肆』 windows下怎麼用python連接hive資料庫

#!/usr/bin/python2.7
#hive--servicehiveserver>/dev/null2>/dev/null&
#/opt/cloudera/parcels/CDH/lib/hive/lib/pyimportsys

#python與hiveserver交互
sys.path.append('C:/hadoop_jar/py')
fromhive_serviceimportThriftHive
fromhive_service.
fromthrift.transportimportTSocket
fromthriftimportThrift
fromthrift.transportimportTTransport
fromthrift.protocolimportTBinaryProtocol

if__name__=='__main__':
try:
socket=TSocket.TSocket('10.70.50.111',10000)
transport=TTransport.TBufferedTransport(socket)
protocol=TBinaryProtocol.TBinaryProtocol(transport)
client=ThriftHive.Client(protocol)
sql='select*fromtest'
transport.open()
client.execute(sql)
withopen('C:/Users/DWJ/Desktop/python2hive.txt','w')asout_file:
whileclient.fetchOne():
out_file.write(client.fetchOne())
transport.close()
exceptThrift.TException,tx:
print'%s'%(tx.message)

其中,C:/hadoop_jar/py里的包來自於hive安裝文件自帶的py,如:/opt/cloudera/parcels/CDH/lib/hive/lib/py,將其添加到python中即可。

熱點內容
深入編譯器 發布:2025-05-15 07:41:35 瀏覽:877
電信手機號服務密碼怎麼查 發布:2025-05-15 07:40:10 瀏覽:613
python全局變數文件 發布:2025-05-15 07:35:06 瀏覽:954
位元組和存儲位元組 發布:2025-05-15 07:32:10 瀏覽:521
linux應用開發工程師 發布:2025-05-15 07:32:07 瀏覽:261
sqldcl 發布:2025-05-15 07:29:18 瀏覽:199
canvas的圖像上傳 發布:2025-05-15 07:29:17 瀏覽:102
離線緩存為什麼點不動 發布:2025-05-15 07:27:17 瀏覽:829
釘鼎伺服器出口ip 發布:2025-05-15 07:13:08 瀏覽:279
移動硬碟和光碟哪個存儲時間長 發布:2025-05-15 07:04:25 瀏覽:489