Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views1 page

Crud

The document provides Python code for connecting to a MySQL database and performing basic CRUD operations. It includes functions to create a connection, insert a new record into the 'users' table, and read records from the same table. Error handling is implemented to manage connection and execution issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Crud

The document provides Python code for connecting to a MySQL database and performing basic CRUD operations. It includes functions to create a connection, insert a new record into the 'users' table, and read records from the same table. Error handling is implemented to manage connection and execution issues.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import mysql.

connector
from mysql.connector import Error

# Establish connection to MySQL


def create_connection():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='12345',
database='test_db' # Replace with your database name
)
if connection.is_connected():
print("Connection successful")
return connection
except Error as e:
print(f"Error: {e}")
return None

# Create operation
def create_record(connection, name, age, city):
try:
cursor = connection.cursor()
query = "INSERT INTO users (name, age, city) VALUES (%s, %s, %s)"
values = (name, age, city)
cursor.execute(query, values)
connection.commit()
print("Record inserted successfully")
except Error as e:
print(f"Error: {e}")

# Read operation
def read_records(connection):
try:
cursor = connection.cursor()
query = "SELECT * FROM users"
cursor.execute(query)
records

You might also like