- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试我在 2016 年的一本书中找到的以下代码:
import MySQLdb
import pandas as pd
# database setup omitted for the sake of brevity
nr_customers = 100
colnames = ["movie%i" %i for i in range(1, 33)]
pd.np.random.seed(2015)
generated_customers = pd.np.random.randint(0,2,32 * nr_customers).reshape(nr_customers,32)
data = pd.DataFrame(generated_customers, columns = list(colnames))
data.to_sql('cust',mc,index=True,if_exists='replace',index_label='cust_id')
它只是给我以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/MySQLdb/cursors.py in execute(self, query, args)
242 try:
--> 243 query = query % args
244 except TypeError as m:
TypeError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
ProgrammingError Traceback (most recent call last)
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1430 else:
-> 1431 cur.execute(*args)
1432 return cur
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/MySQLdb/cursors.py in execute(self, query, args)
244 except TypeError as m:
--> 245 self.errorhandler(self, ProgrammingError, str(m))
246
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/MySQLdb/connections.py in defaulterrorhandler(***failed resolving arguments***)
51 if errorclass is not None:
---> 52 raise errorclass(errorvalue)
53 else:
ProgrammingError: not all arguments converted during string formatting
During handling of the above exception, another exception occurred:
DatabaseError Traceback (most recent call last)
<ipython-input-24-125bb185f2f4> in <module>
4 generated_customers = pd.np.random.randint(0,2,32 * nr_customers).reshape(nr_customers,32)
5 data = pd.DataFrame(generated_customers, columns = list(colnames))
----> 6 data.to_sql('cust',mc,index=True,if_exists='replace',index_label='cust_id')
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/core/generic.py in to_sql(self, name, con, schema, if_exists, index, index_label, chunksize, dtype, method)
2529 sql.to_sql(self, name, con, schema=schema, if_exists=if_exists,
2530 index=index, index_label=index_label, chunksize=chunksize,
-> 2531 dtype=dtype, method=method)
2532
2533 def to_pickle(self, path, compression='infer',
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in to_sql(frame, name, con, schema, if_exists, index, index_label, chunksize, dtype, method)
458 pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index,
459 index_label=index_label, schema=schema,
--> 460 chunksize=chunksize, dtype=dtype, method=method)
461
462
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in to_sql(self, frame, name, if_exists, index, index_label, schema, chunksize, dtype, method)
1544 if_exists=if_exists, index_label=index_label,
1545 dtype=dtype)
-> 1546 table.create()
1547 table.insert(chunksize, method)
1548
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in create(self)
570
571 def create(self):
--> 572 if self.exists():
573 if self.if_exists == 'fail':
574 raise ValueError(
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in exists(self)
558
559 def exists(self):
--> 560 return self.pd_sql.has_table(self.name, self.schema)
561
562 def sql_schema(self):
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in has_table(self, name, schema)
1556 "WHERE type='table' AND name={wld};").format(wld=wld)
1557
-> 1558 return len(self.execute(query, [name, ]).fetchall()) > 0
1559
1560 def get_table(self, table_name, schema=None):
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1443 "Execution failed on sql '{sql}': {exc}".format(
1444 sql=args[0], exc=exc))
-> 1445 raise_with_traceback(ex)
1446
1447 @staticmethod
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/compat/__init__.py in raise_with_traceback(exc, traceback)
418 if traceback == Ellipsis:
419 _, _, traceback = sys.exc_info()
--> 420 raise exc.with_traceback(traceback)
421 else:
422 # this version of raise is a syntax error in Python 3
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/pandas/io/sql.py in execute(self, *args, **kwargs)
1429 cur.execute(*args, **kwargs)
1430 else:
-> 1431 cur.execute(*args)
1432 return cur
1433 except Exception as exc:
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/MySQLdb/cursors.py in execute(self, query, args)
243 query = query % args
244 except TypeError as m:
--> 245 self.errorhandler(self, ProgrammingError, str(m))
246
247 if isinstance(query, unicode):
~/anaconda3/envs/TestEnv/lib/python3.7/site-packages/MySQLdb/connections.py in defaulterrorhandler(***failed resolving arguments***)
50 raise errorvalue
51 if errorclass is not None:
---> 52 raise errorclass(errorvalue)
53 else:
54 raise Exception(errorvalue)
DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
我可以在 “DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting”中恢复
我尝试了不同的方法,比如使用 f"${}"等等,但错误是一样的。
代码与书中的不完全相同,因为我必须删除 to_sql
中使用的 flavor = 'mysql'
参数。
我正在使用:
最佳答案
没关系。只是更改为将 sqlalchemy 与 pymysql 一起使用并节省了大量时间和 LOC:
from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://user:password@localhost/database')
...
data.to_sql(table, con = engine)
关于python - "not all arguments converted during string formatting"当to_sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55822497/
我已经阅读了有关不向数据库添加重复记录的 Pandas to_sql 解决方案。我正在处理日志的 csv 文件,每次我上传一个新的日志文件时,我都会读取数据并使用 Pandas 创建一个新的数据框进行
我正在将PANDAS与SQLAlchemy一起使用DataFrame.to_sql写入MYSQL DB。我喜欢打开'append' --> df.to_sql(con=con, name='table
我有一个看起来像这样的数据框 id_1 id_2 id_3 ... date_1 1 3 4 date_2 4
我想将数据帧写入现有的 sqlite(或 mysql)表,有时数据帧将包含数据库中尚不存在的新列。我需要做什么才能避免抛出错误?有没有办法告诉 pandas 或 sqlalchemy 使用潜在的新列自
我正在尝试使用Django的db连接变量将pandas数据帧插入Postgres数据库。我使用的代码是 df.to_sql('forecast',connection,if_exists='appen
我目前正在尝试稍微调整一些脚本的性能,似乎瓶颈始终是使用 pandas to_sql 函数实际插入数据库(=MSSQL)。 造成这种情况的一个因素是 mssql 的参数限制为 2100。 我与 sql
有人经历过这种情况吗? 我有一个包含“int”和“varchar”列的表 - 一个报告时间表。 我正在尝试使用 python 程序将扩展名为“.xls”的 Excel 文件导入到该表中。我正在使用 p
我正在尝试将 pandas 数据框保存为 SQL 文件 我按照文档进行了尝试 from sqlalchemy import create_engine engine = create_engine('
Panda 的 to_sql() 和 if_exists='replace' 为我的表设置了错误的字符集。为了将多个 csv 复制到 mysql 并忽略行上的错误(如重复错误),我首先将 csv 读取
我有一个如下所示的数据框: df = pd.DataFrame(index= pd.date_range('2014-01-01', periods=10)) df['date'] = df.inde
我正在尝试使用 Pandas to_sql 将 .csv 文件中的数据插入到 mssql 数据库中。不管我怎么看,我都会遇到这个错误: pyodbc.DataError: ('String data,
我想不断将数据帧行添加到 MySQL 数据库中,避免任何重复的条目进入 MySQL。 我目前通过使用 df.apply() 遍历每一行并调用 MySQL insert ignore(duplicate
如何使用 df.to_sql(if_exists = 'append') 仅附加数据框和数据库之间的唯一值。换句话说,我想评估 DF 和 DB 之间的重复项,并在写入数据库之前删除这些重复项。 这个有
我有一个订购的 Pandas Dataframe。 a0 b0 c0 d0 370025442 370020440 370020436
我正在尝试使用 Python 的 pandas to_sql 命令将月度数据发送到 MySQL 数据库。我的程序一次运行一个月的数据,我想将新数据附加到现有数据库中。然而,Python 给我一个错误:
我正在使用 df.to_sql(con=con_mysql, name='testdata', if_exists='replace', flavor='mysql') 将数据框导出到 mysql。但
我有一个 1,000,000 x 50 Pandas DataFrame,我目前正在使用以下方法写入 SQL 表: df.to_sql('my_table', con, index=False) 这需
我有一个字符串格式的数字列,我想将它作为 float 发送到 PostresSQL。如何确保 SQLAlchemy 将此列设置为 float ? (请注意,列中可能是 NaN)。这是代码 import
我想在我创建的表格中插入一些数据。我有一个如下所示的数据框: 我创建了一个表: create table online.ds_attribution_probabilities ( attributi
我正在使用 Pandas 0.18.1,在摆弄这段代码时, import pd def getIndividualDf(item): var1 = [] # ... populate
我是一名优秀的程序员,十分优秀!