0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

OperationalError: table xxx already exists を修正する

Posted at

例外の再現

import sqlite3

con = sqlite3.connect('test.sqlite3')
cur = con.cursor()
cur.execute('create table yutai(column1 , column2)')

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
セル11  c:\xxx\test.ipynb in <cell line: 4>()
      2 con = sqlite3.connect('yuutai.sqlite3')
      3 cur = con.cursor()
----> 4 cur.execute('create table  yutai(test1 ,test2)')

OperationalError: table yutai already exists

原因

google翻訳で調べると、OperationalError: テーブル xxx は既に存在しますと表示されます。
テーブルを作成した後に同じテーブルを作成しようとする発生するみたいですね。

解決方法

import sqlite3

con = sqlite3.connect('test.sqlite3')
cur = con.cursor()
cur.execute('create table IF NOT EXISTS yutai(column1 , column2)')

create tableの後に 「 IF NOT EXISTS 」を記述する。
データベースに同じテーブル名が存在していても例外が発生しなくなりました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?