Home > Database > Mysql Tutorial > How to connect to mysql database

How to connect to mysql database

下次还敢
Release: 2024-04-14 19:12:47
Original
1107 people have browsed it

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

How to connect to MySQL database

Step one: Obtain connection information

  • Server address: the IP address or host name of the database server
  • Port: usually 3306
  • Username: the username of the database user
  • Password: Database user’s password
  • Database name: Name of the database to be connected

Step 2: Select the connection method

  • Use Python library (such as MySQLdb or pymysql):

    <code class="python">import mysql.connector
    
    # 创建连接对象
    conn = mysql.connector.connect(
      host="127.0.0.1",
      port=3306,
      user="username",
      password="password",
      database="database_name"
    )</code>
    Copy after login
  • Use command line (such as MySQL):

    <code class="shell">mysql -h 127.0.0.1 -P 3306 -u username -p password database_name</code>
    Copy after login

Step 3: Perform queries and operations

Once the connection is established, you can perform queries and operations using:

  • Execute query:

    <code class="python"># 创建游标对象
    cursor = conn.cursor()
    
    # 执行查询
    cursor.execute("SELECT * FROM table_name")
    
    # 获取结果
    rows = cursor.fetchall()
    
    # 关闭游标
    cursor.close()</code>
    Copy after login
  • Perform update operation:

    <code class="python">cursor.execute("UPDATE table_name SET field_name='new_value' WHERE condition")
    conn.commit()</code>
    Copy after login

Step 4: Close the connection

After the operation is completed, please close the connection to release resources:

<code class="python">conn.close()</code>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template