The following steps are required to establish a MySQL connection: 1. Import the MySQL client library; 2. Create a connection object; 3. Create a cursor object; 4. Execute the query; 5. Retrieve the results; 6. Close the connection.
How to create a MySQL connection
Establishing a MySQL connection requires the following steps:
1. Import the MySQL client library
First, you need to import the necessary MySQL client library, which provides an interface for the application to communicate with the MySQL database.
For Python:
import mysql.connector
For Java:
import java.sql.*;
2. Create a connection object
Create a connection using the client library Object that will represent a connection to the MySQL database.
For Python:
connection = mysql.connector.connect( host="localhost", user="root", password="my_password", database="my_database" )
host
: The address or hostname of the database server user
: Has a connection Permission usernamepassword
: User’s passworddatabase
: Name of the database to be connectedFor Java:
// 使用 JDBC 创建连接对象 Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/my_database", "root", "my_password" );
3. Create a cursor object
Create a cursor object for executing queries and retrieving results.
For Python:
cursor = connection.cursor()
For Java:
Statement statement = connection.createStatement();
4. Execute the query
Use the cursor object to execute the query and put The results are stored in the result set.
For Python:
cursor.execute("SELECT * FROM my_table")
For Java:
ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");
5. Retrieval results
Traverse the result set and retrieve individual rows.
For Python:
for row in cursor.fetchall(): print(row)
For Java:
while (resultSet.next()) { System.out.println(resultSet.getInt("id")); }
6. Close the connection
After using the connection, please close the connection object to release resources.
For Python:
cursor.close() connection.close()
For Java:
statement.close(); connection.close();
The above is the detailed content of How to create a connection in mysql. For more information, please follow other related articles on the PHP Chinese website!