我有一个Excel文件。我将其导入数据框并尝试使用数据更新数据库表。
PLANT_DATA = { 'daisy': 'diasy.csv',
'rose': 'rose.csv',
'cucumber': 'cucumber.csv' }
def filters():
print('Let\'s explore some plant data')
while True:
plant = input("Would you like to see data for Cucumber, Daisy or Rose plants?").lower()
if plant in PLANT_DATA.keys():
try:
print("Looks like you want to hear about {} plants!".format(plant))
break
except ValueError:
print("That is not a valid plant! Please try again.")
filters()
当我执行以上代码块时;我得到
import pyodbc
def get_sale_file():
try:
cnxn = pyodbc.connect('DRIVER=ODBC Driver 17 for SQL Server;'
'SERVER=' + server + ';DATABASE=' + database + ';UID=' + uname + ';PWD=' + pword,
autocommit=False)
files = os.listdir(ile_path)
df = pd.DataFrame()
for f in files:
if (f.endswith('.xlsx') or f.endswith('.xls')):
df = pd.read_excel(os.path.join(sap_file_path, f))
df.to_sql('temptable', cnxn, if_exists='replace')
query = "UPDATE MList AS mas" + \
" SET TTY = temp.[Territory Code] ," + \
" Freq =temp.[Frequency Code]," + \
" FROM temptable AS temp" + \
" WHERE mas.SiteCode = temp.[ri a]"
我在尝试正确的方法吗?除1/12/2019 10:19:45 AM ERROR: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW)")
之外,panad是否还有其他功能可以更新mssql表
如何克服以上错误?
修改 我是否必须事先创建临时表才能加载datafarme?如果是这样,我的文件包含100列的列,则可能会有所不同。(少数列除外)如何确保熊猫仅将少数列加载到模板中?
答案 0 :(得分:0)
您也可以尝试其他软件包,例如pyodbc。 pytds或adodbapi。 第一个非常简单,使用adodbapi,连接配置看起来像
from adodbapi import adodbapi as adba
raw_config_adodbapi = f"PROVIDER=SQLOLEDB.1;Data Source={server};Initial Catalog={database};trusted_connection=no;User ID={user};Password={password};"
conn = adba.connect(raw_config_adodbapi, timeout=120, autocommit=True)
此外,似乎pyodbc的连接字符串中的参数应包含在{}中,但可能不是强制性的。
答案 1 :(得分:0)
根据pandas.DataFrame.to_sql(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html)的指南,该连接需要一个连接类型sqlalchemy.engine.Engine或sqlite3.Connection,然后必须使用这样的连接来更改代码:>
import sqlalchemy
import pyodbc
cnxn = sqlalchemy.create_engine("mssql+pyodbc://<username>:<password>@<dsnname>")
df.to_sql("table_name", cnxn,if_exists='replace')
更新:使用urllib
import urllib
import pyodbc
params = urllib.quote_plus("DRIVER={ODBC Driver 17 for SQL Server};SERVER=yourserver;DATABASE=yourdatabase ;UID=user;PWD=password")
cnxn = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
df.to_sql("table_name", cnxn,if_exists='replace')