python connect to mysql example
The common way to connect to MySQL in Python is to use the PyMySQL library; first install the dependencies through pip install pymysql; then use the pymysql.connect() method to pass in host, user, password, database and other parameters to establish a connection; when operating the database, use the with connection.cursor() to execute SQL statements, use cursor.fetchall() or fetchone() to obtain the results, and write operations such as insertion and update require calling connection.commit() to submit transactions; finally be sure to call connection.close() to close the connection or automatically release resources using the context manager; it is recommended to use %s placeholder to prevent SQL injection; high concurrency scenarios can use connection pools to optimize performance; the complete steps are: 1. Install pymysql; 2. Establish a connection and pass it into the database configuration; 3. Use cursors to execute SQL; 4. Submit transactions (write operations); 5. Close the connection; the above process ensures safe and stable operation of the MySQL database.
Python The common way to connect to MySQL is to use two third-party libraries, PyMySQL
or mysql-connector-python
. The following is a simple and practical example of connecting and operating MySQL using PyMySQL as an example.

✅ Installation dependencies
First install PyMySQL
(if not installed):
pip install pymysql
? Basic connection example
import pymysql # Create a database connection connection = pymysql.connect( host='localhost', # database host address user='your_username', # database username password='your_password', # database password database='your_database', # database name to be connected to port=3306, # port, default 3306 charset='utf8mb4' # It is recommended to use utf8mb4 to support emoji ) try: with connection.cursor() as cursor: # Execute SQL query sql = "SELECT * FROM users LIMIT 5" cursor.execute(sql) # Get the query result = cursor.fetchall() for row in result: print(row) # If it is a write operation (INSERT/UPDATE/DELETE), a transaction needs to be submitted # connection.commit() Finally: # Close the database connection.close()
? Common operation examples
1. Insert data
with connection.cursor() as cursor: sql = "INSERT INTO users (name, email) VALUES (%s, %s)" cursor.execute(sql, ('Alice', 'alice@example.com')) # Remember to submit connection.commit()
2. Query a single record
with connection.cursor() as cursor: sql = "SELECT id, name FROM users WHERE name = %s" cursor.execute(sql, ('Alice',)) result = cursor.fetchone() print(result) # Output such as: (1, 'Alice')
3. Update data
with connection.cursor() as cursor: sql = "UPDATE users SET email = %s WHERE name = %s" cursor.execute(sql, ('new_email@example.com', 'Alice')) connection.commit()
?️ Best Practice Recommendations
- Use
with
to manage cursors and close automatically. -
connection.commit()
must be called after the write operation. - Use
%s
placeholder to prevent SQL injection and do not splice strings. - Remember
close()
after the connection is complete, or use the context manager.
? Use connection pool (optional advanced)
For high concurrency scenarios, it is recommended to use DBUtils
connection pool to avoid frequent connection creation.

Basically that's it. Just replace the database information with your own, and the above code can be run directly. Not complicated, but it is easy to ignore commit and exception handling.
The above is the detailed content of python connect to mysql example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

To get started with quantum machine learning (QML), the preferred tool is Python, and libraries such as PennyLane, Qiskit, TensorFlowQuantum or PyTorchQuantum need to be installed; then familiarize yourself with the process by running examples, such as using PennyLane to build a quantum neural network; then implement the model according to the steps of data set preparation, data encoding, building parametric quantum circuits, classic optimizer training, etc.; in actual combat, you should avoid pursuing complex models from the beginning, paying attention to hardware limitations, adopting hybrid model structures, and continuously referring to the latest documents and official documents to follow up on development.

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

To master Python web crawlers, you need to grasp three core steps: 1. Use requests to initiate a request, obtain web page content through get method, pay attention to setting headers, handling exceptions, and complying with robots.txt; 2. Use BeautifulSoup or XPath to extract data. The former is suitable for simple parsing, while the latter is more flexible and suitable for complex structures; 3. Use Selenium to simulate browser operations for dynamic loading content. Although the speed is slow, it can cope with complex pages. You can also try to find a website API interface to improve efficiency.

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

Use httpx.AsyncClient to efficiently initiate asynchronous HTTP requests. 1. Basic GET requests manage clients through asyncwith and use awaitclient.get to initiate non-blocking requests; 2. Combining asyncio.gather to combine with asyncio.gather can significantly improve performance, and the total time is equal to the slowest request; 3. Support custom headers, authentication, base_url and timeout settings; 4. Can send POST requests and carry JSON data; 5. Pay attention to avoid mixing synchronous asynchronous code. Proxy support needs to pay attention to back-end compatibility, which is suitable for crawlers or API aggregation and other scenarios.

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string
