fork download
  1. import mysql.connector
  2.  
  3. # Connect to MySQL server
  4. db = mysql.connector.connect(
  5. host="localhost",
  6. user="your_username",
  7. password="your_password"
  8. )
  9.  
  10. cursor = db.cursor()
  11.  
  12. # Create a new database
  13. cursor.execute("CREATE DATABASE mydatabase")
  14.  
  15. # Use the new database
  16. cursor.execute("USE mydatabase")
  17.  
  18. # Create a new table
  19. cursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")
  20.  
  21. # Insert records
  22. query = "INSERT INTO students (name, age) VALUES (%s, %s)"
  23. values = [
  24. ("John", 20),
  25. ("Amy", 22),
  26. ("Mark", 19)
  27. ]
  28. cursor.executemany(query, values)
  29. db.commit()
  30.  
  31. # Retrieve all records
  32. cursor.execute("SELECT * FROM students")
  33. records = cursor.fetchall()
  34. for record in records:
  35. print(record)
  36.  
  37. # Update a record
  38. cursor.execute("UPDATE students SET age = 21 WHERE name = 'John'")
  39. db.commit()
  40.  
  41. # Retrieve and print the updated record
  42. cursor.execute("SELECT * FROM students WHERE name = 'John'")
  43. record = cursor.fetchone()
  44. print(record)
  45.  
  46. # Delete a record
  47. cursor.execute("DELETE FROM students WHERE name = 'Mark'")
  48. db.commit()
  49.  
  50. # Retrieve all records again
  51. cursor.execute("SELECT * FROM students")
  52. records = cursor.fetchall()
  53. for record in records:
  54. print(record)
  55.  
Success #stdin #stdout 0.02s 25976KB
stdin
Standard input is empty
stdout
import mysql.connector

# Connect to MySQL server
db = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password"
)

cursor = db.cursor()

# Create a new database
cursor.execute("CREATE DATABASE mydatabase")

# Use the new database
cursor.execute("USE mydatabase")

# Create a new table
cursor.execute("CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT)")

# Insert records
query = "INSERT INTO students (name, age) VALUES (%s, %s)"
values = [
    ("John", 20),
    ("Amy", 22),
    ("Mark", 19)
]
cursor.executemany(query, values)
db.commit()

# Retrieve all records
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
for record in records:
    print(record)

# Update a record
cursor.execute("UPDATE students SET age = 21 WHERE name = 'John'")
db.commit()

# Retrieve and print the updated record
cursor.execute("SELECT * FROM students WHERE name = 'John'")
record = cursor.fetchone()
print(record)

# Delete a record
cursor.execute("DELETE FROM students WHERE name = 'Mark'")
db.commit()

# Retrieve all records again
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
for record in records:
    print(record)