search
HomeBackend DevelopmentPython TutorialHow to handle database operations in Python

How to handle database operations in Python

Oct 09, 2023 pm 06:44 PM
pythonDatabase operationsdeal with

How to handle database operations in Python

How to handle database operations in Python

As a high-level programming language, Python is very suitable for handling database operations. It has simple and easy-to-use syntax and rich third-party libraries, allowing developers to easily connect, query and modify databases. In this article, we will introduce how to use Python for database operations and provide specific code examples.

Before we begin, we need to install the Python database driver. Common database drivers include psycopg2, MySQL Connector/Python and PyMongo, which are used to connect to PostgreSQL, MySQL and MongoDB databases respectively. We can use the pip command to install, for example:

pip install psycopg2    # 连接 PostgreSQL
pip install mysql-connector-python    # 连接 MySQL
pip install pymongo    # 连接 MongoDB

After installing the database driver, we can start database operations. Below are some examples of common database operations.

  1. Connect to the database

Before performing database operations, we first need to connect to the database. Each database driver has different functions to achieve connection. The following is the sample code to connect PostgreSQL, MySQL and MongoDB:

import psycopg2    # PostgreSQL
conn1 = psycopg2.connect(database="mydb", user="myuser", password="mypassword", host="localhost", port="5432")

import mysql.connector    # MySQL
conn2 = mysql.connector.connect(user='myuser', password='mypassword', host='localhost', database='mydb')

import pymongo    # MongoDB
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydb"]
  1. Query data

Query data is Common requirements in database operations. The following are some sample codes that demonstrate how to query data in PostgreSQL, MySQL and MongoDB:

# PostgreSQL
cur1 = conn1.cursor()
cur1.execute("SELECT * from mytable")
rows1 = cur1.fetchall()
for row in rows1:
    print(row)

# MySQL
cur2 = conn2.cursor()
cur2.execute("SELECT * from mytable")
rows2 = cur2.fetchall()
for row in rows2:
    print(row)

# MongoDB
col = db["mycollection"]
docs = col.find()
for doc in docs:
    print(doc)
  1. Insert data

In addition to querying data, we often need to Insert new data into the database. The following is some sample code that demonstrates how to insert data into PostgreSQL, MySQL and MongoDB:

# PostgreSQL
cur1 = conn1.cursor()
cur1.execute("INSERT INTO mytable (column1, column2) VALUES (%s, %s)", ("value1", "value2"))
conn1.commit()

# MySQL
cur2 = conn2.cursor()
cur2.execute("INSERT INTO mytable (column1, column2) VALUES (%s, %s)", ("value1", "value2"))
conn2.commit()

# MongoDB
col = db["mycollection"]
doc = { "column1": "value1", "column2": "value2" }
col.insert_one(doc)
  1. Update and delete data

Finally, we also need to understand how Update and delete data in the database. The following are some sample codes that demonstrate how to update and delete data in PostgreSQL, MySQL and MongoDB:

# PostgreSQL
cur1 = conn1.cursor()
cur1.execute("UPDATE mytable SET column1 = %s WHERE column2 = %s", ("newvalue1", "value2"))
conn1.commit()

# MySQL
cur2 = conn2.cursor()
cur2.execute("UPDATE mytable SET column1 = %s WHERE column2 = %s", ("newvalue1", "value2"))
conn2.commit()

# MongoDB
col = db["mycollection"]
col.update_one({ "column2": "value2" }, { "$set": { "column1": "newvalue1" } })

# 删除数据
# PostgreSQL
cur1 = conn1.cursor()
cur1.execute("DELETE FROM mytable WHERE column2 = %s", ("value2",))
conn1.commit()

# MySQL
cur2 = conn2.cursor()
cur2.execute("DELETE FROM mytable WHERE column2 = %s", ("value2",))
conn2.commit()

# MongoDB
col = db["mycollection"]
col.delete_one({ "column2": "value2" })

The above are some basic database operation examples, I hope it can help everyone deal with database operation problems in Python Helps. Python's database operation functions are very powerful and can meet most development needs. Choose the appropriate database driver according to the actual situation and follow the above examples. I believe you will handle database operations easily.

The above is the detailed content of How to handle database operations in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment