在天行資料通過API拿到資料並放入資料庫

2021-10-09 14:38:58 字數 2259 閱讀 3802

先建立資料庫與表,記得設定字元編碼為utf8。否則存中文會報錯。

create

database news default

character

set utf8;

create

table tb_newslist (

id int

auto_increment

primary

key,

title varchar

(100

)default'',

url varchar

(150))

;

通過requests獲得資料,連線資料庫,並將資料寫入。

import requests

import pymysql

key =

'7e45e6dd2okjygf7d2b5e4d7137uyd42'

news_dict =

for page in

range(1

,11):

resp = requests.get(f''

)for data_dict in resp.json()[

"newslist"]:

news_dict[data_dict[

'title']]

= data_dict[

'url'

]conn = pymysql.connect(host=

'59.119.250.88'

, port=

3306

, database=

'news'

, charset=

'utf8'

, user=

'root'

, password=

'tianmao.520'

, autocommit=

false

)try

:# 獲取游標

with conn.cursor(

)as cursor:

# 通過游標對資料庫操作

for new in news_dict:

result = cursor.execute(

'insert into tb_newslist(title, url) values (%s,%s)'

,(new, news_dict[new]))

# 操作成功,提交

conn.commit(

)except pymysql.mysqlerror as err:

print

(err)

# 操作失敗,回滾

conn.rollback(

)finally

:# 關閉連線

conn.close(

)

import pymysql

conn = pymysql.connect(host=

'59.119.250.88'

, port=

3306

, database=

'news'

, charset=

'utf8'

, user=

'root'

, password=

'tianmao.520'

, autocommit=

false

)name =

input

('請輸入查詢內容'

)try

:# 獲取游標

with conn.cursor(

)as cursor:

# 通過游標對資料庫操作

cursor.execute(

'select title, url from tb_newslist where title like %s'

,(f'%%'))

for new in cursor.fetchall():

print

(new)

except pymysql.mysqlerror as err:

print

(err)

finally

:# 關閉連線

conn.close(

)

Bundle資料通過Message傳送

bundle作用 activity之間訪問資料用。是乙個鍵值對。提供了一系列方法用於儲存資料。bundle用法,通過message傳送 建立物件 bundle bundle new bundle 存資料,put各種資料型別,putstring putint,我這裡是李剛老師的calprime例程的。...

hive資料通過hfile匯入hbase

hdfs dfs ls tmp student baseinfo建立對應的hbase表,其中baseinfo為family,應和上一步對應 create student info baseinfo 執行bulkhead,將資料匯入到hbase中 bin hbase org.apache.hadoop...

如何將JSON資料通過Get方法獲取資料

介面格式如下 imuser getcontact?getcontact userid 9 其中 userid 9 為json格式 我是用asihttprequest來請求資料的,方法如下 nsmutabledictionary mudic nsmutabledictionary alloc init...