|
| 1 | +# Code Sample from the tutorial at https://learncodeshare.net/2015/07/09/delete-crud-using-cx_oracle/ |
| 2 | +# section titled "Resetting the data" |
| 3 | +# The following resets the data for use with the update section |
| 4 | +# For both tables: |
| 5 | +# Table data is removed. |
| 6 | +# The identity column is set to start with the id after the starting data. |
| 7 | +# Using the executemany function an array of starting data is inserted into the table. |
| 8 | + |
| 9 | +import cx_Oracle |
| 10 | +import os |
| 11 | +connectString = os.getenv('DB_CONNECT') # The environment variable for the connect string: DB_CONNECT=user/password@database |
| 12 | +con = cx_Oracle.connect(connectString) |
| 13 | +cur = con.cursor() |
| 14 | + |
| 15 | +# Delete rows |
| 16 | +statement = 'delete from lcs_pets' |
| 17 | +cur.execute(statement) |
| 18 | + |
| 19 | +# Reset Identity Coulmn |
| 20 | +statement = 'alter table lcs_pets modify id generated BY DEFAULT as identity (START WITH 8)' |
| 21 | +cur.execute(statement) |
| 22 | + |
| 23 | +# Delete rows |
| 24 | +statement = 'delete from lcs_people' |
| 25 | +cur.execute(statement) |
| 26 | + |
| 27 | +# Reset Identity Coulmn |
| 28 | +statement = 'alter table lcs_people modify id generated BY DEFAULT as identity (START WITH 8)' |
| 29 | +cur.execute(statement) |
| 30 | + |
| 31 | +# Insert default rows |
| 32 | +rows = [{'id':1, 'name':'Bob', 'age':35, 'notes':'I like dogs'}, |
| 33 | + {'id':2, 'name':'Kim', 'age':27, 'notes':'I like birds'}, |
| 34 | + {'id':3, 'name':'Cheryl', 'age':23, 'notes':'I like horses'}, |
| 35 | + {'id':4, 'name':'Bob', 'age':27, 'notes':'I like rabbits'}, |
| 36 | + {'id':5, 'name':'Stacey', 'age':45, 'notes':'I like snakes'}, |
| 37 | + {'id':6, 'name':'Pete', 'age':23, 'notes':'I like cats'}, |
| 38 | + {'id':7, 'name':'Pat', 'age':36, 'notes':'I like dogs'}] |
| 39 | +cur.bindarraysize = 2 |
| 40 | +cur.executemany("insert into lcs_people(id, name, age, notes) values (:id, :name, :age, :notes)", rows) |
| 41 | +con.commit() |
| 42 | + |
| 43 | +# Insert default rows |
| 44 | +rows = [{'id':1, 'name':'Duke', 'owner':1, 'type':'dog'}, |
| 45 | + {'id':2, 'name':'Dragon', 'owner':2, 'type':'bird'}, |
| 46 | + {'id':3, 'name':'Sneaky', 'owner':5, 'type':'snake'}, |
| 47 | + {'id':4, 'name':'Red', 'owner':2, 'type':'bird'}, |
| 48 | + {'id':5, 'name':'Red', 'owner':3, 'type':'horse'}, |
| 49 | + {'id':6, 'name':'Buster', 'owner':1, 'type':'dog'}, |
| 50 | + {'id':7, 'name':'Fido', 'owner':7, 'type':'cat'}] |
| 51 | +cur.bindarraysize = 2 |
| 52 | +cur.executemany("insert into lcs_pets (id, name, owner, type) values (:id, :name, :owner, :type)", rows) |
| 53 | +con.commit() |
| 54 | + |
| 55 | +cur.close() |
0 commit comments