Python データフレームを SQL テーブルに挿入する際に列名で全角記号を使う方法

H.S 40 Reputation points
2023-12-25T09:07:36.7066667+00:00

Python で pyodbc パッケージを使用して、SQL データベースに pandas データフレームを挿入する方法を検討しております。

しかしながら、Insertするデータの列名に全角の記号(具体的には全角のカッコ()やスラッシュ/、アットマーク@)がある場合、

SyntaxError: invalid character

とエラーが出てしまいます。

エラー回避策について教えていただけますでしょうか。

よろしくお願いいたします。

一部の列名(3つ目の列を"(/)@"に変更)として実行してみるとエラーが発生します。

実行コード(今回問題部分になっている箇所のみ):

cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
     cursor.execute("INSERT INTO [dbo].[inserttest] (DepartmentID,Name,(/)@) values(?,?,?)", row.DepartmentID, row.Name, row.(/)@)
cnxn.commit()
cursor.close()

実行結果(row.(/)@ のところでエラー):

cursor.execute("INSERT INTO [dbo].[inserttest] (DepartmentID,Name,(/)@) values(?,?,?)", row.DepartmentID, row.Name, row.(/)@)
                                                                                                                            
SyntaxError: invalid character '(' (U+FF08)
SQL Server Other
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-12-25T10:46:27.24+00:00

    This is an English-language forum, and I am sorry, but I don't speak Japanese/Chinese.

    Furthermore, you have labelled this SQL Server. But I don't recognise that as an error message from SQL Server, but I will assume that this is from Python.

    Then again, what comes after Name in the INSERT statement, does not seem to make sense from an SQL perspective. But I since I can't read your post, I don't know what you are trying to achieve.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.