Skip to content

Commit

Permalink
BUG: Fix if_exists='replace' functionality in io.sql.write_frame
Browse files Browse the repository at this point in the history
This should resolve issues pandas-dev#2971 and pandas-dev#4110
  • Loading branch information
davidshinn committed Jul 28, 2013
1 parent 0c14a1a commit 28f9b74
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
4 changes: 2 additions & 2 deletions pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,13 @@ def write_frame(frame, name, con, flavor='sqlite', if_exists='fail', **kwargs):
#create or drop-recreate if necessary
create = None
if exists and if_exists == 'replace':
create = "DROP TABLE %s" % name
create = "DROP TABLE %s;" % name + get_schema(frame, name, flavor)
elif not exists:
create = get_schema(frame, name, flavor)

if create is not None:
cur = con.cursor()
cur.execute(create)
cur.executescript(create)
cur.close()

cur = con.cursor()
Expand Down
14 changes: 14 additions & 0 deletions pandas/io/tests/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ def test_if_exists(self):
df_if_exists_1 = DataFrame({'col1': [1, 2], 'col2': ['A', 'B']})
df_if_exists_2 = DataFrame({'col1': [3, 4, 5], 'col2': ['C', 'D', 'E']})
table_name = 'table_if_exists'
sql_select = "SELECT * FROM %s" % table_name

# test if invalid value for if_exists raises appropriate error
self.assertRaises(ValueError,
Expand All @@ -258,6 +259,19 @@ def test_if_exists(self):
cur.execute("DROP TABLE %s" % table_name)
cur.close()

# test if_exists='replace'
sql.write_frame(frame=df_if_exists_1, con=self.db, name=table_name,
flavor='sqlite', if_exists='replace')
sql.write_frame(frame=df_if_exists_2, con=self.db, name=table_name,
flavor='sqlite', if_exists='replace')
self.assertEqual(sql.tquery(sql_select, con=self.db),
[(3, 'C'), (4, 'D'), (5, 'E')])
if sql.table_exists(table_name, self.db, flavor='sqlite'):
cur = self.db.cursor()
cur.execute("DROP TABLE %s" % table_name)
cur.close()



class TestMySQL(unittest.TestCase):

Expand Down

0 comments on commit 28f9b74

Please sign in to comment.