Ask Your Question
1

How do you log Python data into a database?

asked 2022-06-13 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-06-19 19:00:00 +0000

scrum gravatar image

updated 2023-04-10 15:33:32 +0000

qstack gravatar image

There are several ways to log Python data into a database:

  1. Using SQL: You can use SQL to connect to the database and execute SQL statements to insert data into tables.

Example:

import sqlite3

# Connect to database
conn = sqlite3.connect('example.db')
c = conn.cursor()

# Insert data into table
c.execute(\"INSERT INTO my_table (column1, column2) VALUES ('data1', 'data2')\")

# Commit changes
conn.commit()

# Close database connection
conn.close()
  1. Using an ORM (Object-Relational Mapping) library: ORM libraries like SQLAlchemy provide a higher level of abstraction to interact with databases. You can define database models as Python classes and use methods like add() to insert data into the database.

Example:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# Define database model
Base = declarative_base()
class MyTable(Base):
     __tablename__ = 'my_table'
    id = Column(Integer, primary_key=True)
    column1 = Column(String)
    column2 = Column(String)

# Connect to database and create session
engine = create_engine('sqlite:///example.db')
Session = sessionmaker(bind=engine)
session = Session()

# Insert data into table
data = MyTable(column1='data1', column2='data2')
session.add(data)
session.commit()

# Close session
session.close()
  1. Using NoSQL database: If you're working with a NoSQL database like MongoDB, you can use a library like PyMongo to insert data into collections.

Example:

from pymongo import MongoClient

# Connect to MongoDB and get collection
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
collection = db['my_collection']

# Insert data into collection
data = {'column1': 'data1', 'column2': 'data2'}
collection.insert_one(data)
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-13 11:00:00 +0000

Seen: 20 times

Last updated: Apr 10 '23