Write data to Access database using Python

Here’s an example code in Python to write data to an Access database using the pyodbc library

import pyodbc

# Define the data to be written
data = [
    ('John', 25, 'Male'),
    ('Sarah', 30, 'Female'),
    ('David', 22, 'Male')
]

# Define the connection string to the Access database
conn_str = (
    r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
    r'DBQ=C:\path\to\database.accdb;'
)

# Establish a connection to the Access database
conn = pyodbc.connect(conn_str)

# Define a cursor object to execute SQL statements
cursor = conn.cursor()

# Define the SQL statement to insert data into the table
sql = 'INSERT INTO my_table (Name, Age, Gender) VALUES (?, ?, ?)'

# Execute the SQL statement to insert data into the table row by row
for row in data:
    cursor.execute(sql, row)
    conn.commit()

print('Data has been written to the Access database successfully.')

# Close the cursor and the connection
cursor.close()
conn.close()

This code defines a list of data to be written to an Access database table, sets the connection string to the Access database, establishes a connection to the database, defines a cursor object to execute SQL statements, defines the SQL statement to insert data into the table, and executes the SQL statement to insert data into the table row by row using the execute() method. Finally, it prints a message to indicate that the data has been written successfully, and closes the cursor and the connection.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech