簡單粗暴直接上**:
import pymysql
import requests
from lxml import etree
def connect():
# 連線本地資料庫
db = pymysql.connect(host='localhost',
user='root',
password='bbqbbq',
database='stock',
charset='utf8',
cursorclass=pymysql.cursors.dictcursor)
try:
# 使用cursor()建立游標物件cursor
cursor = db.cursor()
# 使用execute()方法執行sql drop: 如果表存在則刪除
cursor.execute("drop table if exists stockinfo")
# 建立表語句
# engine=innodb使用innodb引擎,為mysql ab發布binary的標準之一.
# default charset=utf8 資料庫預設編碼為utf-8
sql = """
create table stockinfo(
id int(11) not null primary key auto_increment,
stockid int(11) not null,
stockname varchar(64) not null)
engine=innodb default charset=utf8;
"""# 執行sql語句
cursor.execute(sql)
# 插入資料
for stock in get_stock():
stockid = stock.replace("(",",").replace(")","").split(",")[1].strip()
stockname = stock.replace("(",",").replace(")","").split(",")[0].strip()
print(stockid, stockname)
sql_stock = """insert into stockinfo (stockid, stockname) values('%s', '%s')""" %(stockid, stockname)
# 執行sql語句
cursor.execute(sql_stock)
# 提交**並儲存變化
db.commit()
print("**執行完畢!")
except pymysql.error as err:
print(err)
finally:
cursor.close()
db.close()
def get_stock():
# 所有a股**列表
url = ""
response = requests.get(url, headers=headers)
response.encoding = "gbk"
e = etree.html(response.text)
stock_list = e.xpath( '//div[@class="quotebody"]//ul/li/a/text()')
return stock_list
if __name__ == "__main__":
connect()
注意:
sql_stock = """insert into stockinfo (stockid, stockname) values('%s', '%s')""" %(stockid, stockname)
這裡的values() 值要加入單引號或雙引號哦
Python使用pymysql鏈結mysql資料庫
先安裝pymysql如下圖 author pythontab.com 可有可無 匯入pymysql的包 import pymysql try 獲取乙個資料庫連線,注意如果是utf 8型別的,需要制定資料庫 conn pymysql.connect host localhost user root p...
Python使用PyMySQL連線MySQL資料庫
目錄 環境要求 安裝 示例mysql 版本 因為我們本地安裝python的時候,一般都會安裝好pip工具,所以我們可以直接使用pip命令安裝pymysql 如果不會安裝python的朋友們可以看下我的安裝python文章 pip install pymysql出現以下提示就表示安裝成功了 windo...
pymysql包使用(python操縱mysql)
4 更新資料 5 刪除資料 import pymysql db pymysql.connect host localhost user root password 123 port 3306 cursor db.cursor cursor 方法獲取mysql操縱游標,用於執行sql語句 cursor...