Connecting to the MySQL database requires the following steps: Obtain connection information: server address, port, user name, password, database name. Choose a connection method: You can use a Python library (such as MySQLdb or pymysql) or the command line (such as MySQL). Perform queries and operations: After the connection is established, queries and update operations can be performed. Close connection: After the operation is completed, close the connection to release resources.
How to connect to MySQL database
Step one: Obtain connection information
Step 2: Select the connection method
Use Python library (such as MySQLdb or pymysql):
import mysql.connector # 创建连接对象 conn = mysql.connector.connect( host="127.0.0.1", port=3306, user="username", password="password", database="database_name" )
Use command line (such as MySQL):
mysql -h 127.0.0.1 -P 3306 -u username -p password database_name
Step 3: Perform queries and operations
Once the connection is established, you can perform queries and operations using:
Execute query:
# 创建游标对象 cursor = conn.cursor() # 执行查询 cursor.execute("SELECT * FROM table_name") # 获取结果 rows = cursor.fetchall() # 关闭游标 cursor.close()
Perform update operation:
cursor.execute("UPDATE table_name SET field_name='new_value' WHERE condition") conn.commit()
Step 4: Close the connection
After the operation is completed, please close the connection to release resources:
conn.close()
The above is the detailed content of How to connect to mysql database. For more information, please follow other related articles on the PHP Chinese website!