-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
47 lines (38 loc) · 1.13 KB
/
database.py
File metadata and controls
47 lines (38 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import mysql.connector
def setup():
# Set up a connection to the MySQL server
cnx = mysql.connector.connect(
host='localhost',
user='root',
password='AS324S1'
)
# Create a cursor object to execute queries
cursor = cnx.cursor()
# Check if the database exist
cursor.execute("SHOW DATABASES LIKE 'mydatabase'")
exists = cursor.fetchone()
if exists:
print("The database already exists")
else:
# Create the database if it doesn't exist
cursor.execute("CREATE DATABASE mydatabase")
print("The database was created")
# Connect to the database
cnx.database = "mydatabase"
# Create a table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS mytable (
name VARCHAR(255) PRIMARY KEY,
activity VARCHAR(255)
)
""")
# Insert some data into the table
# data = [
# ("test1", "1 1"),
# ]
# cursor.executemany("INSERT INTO mytable (name, age) VALUES (%s, %s)", data)
# Commit the changes to the database
cnx.commit()
# Close the cursor and connection
cursor.close()
cnx.close()