diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 588ffa4b93933..ec04a175b2669 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -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() diff --git a/pandas/io/tests/test_sql.py b/pandas/io/tests/test_sql.py index 0035bd2b79236..9240081858bc1 100644 --- a/pandas/io/tests/test_sql.py +++ b/pandas/io/tests/test_sql.py @@ -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, @@ -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):