first_project
This commit is contained in:
45
add_id_column.py
Normal file
45
add_id_column.py
Normal file
@@ -0,0 +1,45 @@
|
||||
|
||||
import mysql.connector
|
||||
|
||||
def get_connection_details():
|
||||
details = {}
|
||||
with open('setting.txt', 'r') as f:
|
||||
for line in f:
|
||||
key, value = line.strip().split(':', 1)
|
||||
details[key.strip()] = value.strip()
|
||||
return details
|
||||
|
||||
def alter_table():
|
||||
try:
|
||||
config = get_connection_details()
|
||||
conn = mysql.connector.connect(
|
||||
host=config.get('Host'),
|
||||
port=config.get('Port'),
|
||||
user=config.get('Username'),
|
||||
password=config.get('Password'),
|
||||
database=config.get('Database')
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Check if the id column already exists
|
||||
cursor.execute("SHOW COLUMNS FROM extension_data LIKE 'id'")
|
||||
result = cursor.fetchone()
|
||||
|
||||
if not result:
|
||||
# Add the id column with auto-increment
|
||||
alter_query = "ALTER TABLE extension_data ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY FIRST"
|
||||
cursor.execute(alter_query)
|
||||
conn.commit()
|
||||
print("Table 'extension_data' altered successfully. `id` column added.")
|
||||
else:
|
||||
print("Column 'id' already exists in 'extension_data'.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
finally:
|
||||
if 'conn' in locals() and conn.is_connected():
|
||||
cursor.close()
|
||||
conn.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
alter_table()
|
Reference in New Issue
Block a user