Docker+Mysql

Below is a detailed, step-by-step guide on how to use Docker on Windows 10 to run a MySQL container and import the provided SQL dump (located at D:\Desktop\pms_backup.sql). This guide assumes you already have Docker Desktop for Windows installed. If not, first download and install it from Docker’s official website.


1. Pull the MySQL Docker Image

Open a Command Prompt or PowerShell window and pull the official MySQL image (for example, version 8.0) from Docker Hub:

docker pull mysql:8.0

This command downloads the latest MySQL 8.0 image. You can replace 8.0 with any other supported version if needed.


2. Run the MySQL Container with a Volume Mapping

When running the container, you want to map a local directory (in this case, your desktop) to a directory inside the container. This makes it easier to access your SQL dump file from the container. In your example, the dump file is at D:\Desktop\pms_backup.sql. You can map D:\Desktop to a container directory (e.g., /docker-volume).

Run the following command (customizing the root password and names as required):

docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=my-secret-pw -v "D:\Desktop":/docker-volume -p 3306:3306 -d mysql:8.0

(The command starts a MySQL container with a custom root password, maps your desktop folder to the container, exposes the MySQL port, and runs it in the background.)
Explanation:

  • --name mysql-container: Names your container for easier reference.
  • -e MYSQL_ROOT_PASSWORD=my-secret-pw: Sets the root password (replace my-secret-pw with a strong password).
  • -v "D:\Desktop":/docker-volume: Maps your local D:\Desktop folder to /docker-volume inside the container.
  • -p 3306:3306: Exposes the container’s port 3306 (MySQL’s default port) to your host.
  • -d mysql:8.0: Runs the container in detached mode using the MySQL 8.0 image.

Give the container a minute or two to initialize before proceeding.


3. Verify the Container Is Running

Check the status of your container using:

docker ps

You should see your mysql-container in the list. If not, you might need to check the logs:

docker logs mysql-container

Look for messages indicating that MySQL has finished initialization and is ready to accept connections.


4. Import the SQL Dump into MySQL

You have two common methods to import your SQL dump into the running MySQL container:

Method A: Import Directly from the Host

You can run the following command from your Command Prompt or PowerShell. The command connects to the MySQL process running in the container and imports the dump file directly:

docker exec -i mysql-container mysql -uroot -pmy-secret-pw < "D:\Desktop\pms_backup.sql"

Explanation:

  • docker exec -i mysql-container: Executes a command inside the running container.
  • mysql -uroot -pmy-secret-pw: Invokes the MySQL client inside the container, logging in as the root user. Ensure the password matches what you set in the run command.
  • < "D:\Desktop\pms_backup.sql": Redirects your SQL dump file’s contents into the MySQL client.

Method B: Import from Inside the Container

Alternatively, you can enter the container’s shell, then run the MySQL client from within:

  1. Get a bash shell inside the container:

    docker exec -it mysql-container bash
    
  2. Now, from the container’s shell, run:

    mysql -uroot -pmy-secret-pw < /docker-volume/pms_backup.sql
    

This command works because your local D:\Desktop is mounted to /docker-volume in the container.

Choose the method that you find most convenient. In many cases, Method A is simpler as it avoids manually entering the container.


5. Verify the Import

After the import finishes, you might want to verify that the data is now present in your MySQL server. You can do this by accessing the MySQL shell:

docker exec -it mysql-container mysql -uroot -pmy-secret-pw

Then list your databases:

SHOW DATABASES;

If you had specified a particular database for your dump (or if the dump file contains commands to create the database), you should see it listed. You can then use SQL queries to confirm that your tables and data are in place.


Final Notes

  • Permissions: Ensure that the user running Docker has appropriate permissions to access D:\Desktop on your Windows machine.
  • File Paths: If you encounter issues with the path format in Windows (especially in PowerShell), double-check that the path is quoted properly (as shown above).
  • Container Lifecycle: If you ever need to stop or remove the container, you can use:
    • To stop: docker stop mysql-container
    • To remove: docker rm mysql-container
  • Persistent Data: If you need data to persist across container restarts, consider mapping a Docker volume or a dedicated folder for MySQL data (using the -v flag for /var/lib/mysql).

Following these steps should allow you to set up your own MySQL instance in Docker and import the SQL dump with minimal hassle. Enjoy testing your friend’s data locally!

This error generally means that the import process doesn’t know which database to load the data into. When you run the command without specifying a database, MySQL expects that the dump file itself contains a statement (like a USE database_name;) to select the target database. In your case, it appears that either:

  • The dump file does not include a USE [database_name]; statement, or
  • The database creation commands are not included, so MySQL doesn’t know where to import the tables.

How to Resolve It

1. Create the Database First and Specify It During the Import

If your dump file does not explicitly define the target database, you can manually create the database before importing. For example:

  1. Connect to your MySQL container:

    docker exec -it mysql-container mysql -uroot -pmy-secret-pw
    
  2. Create the database:

    CREATE DATABASE my_database;
    
  3. Exit the MySQL shell by typing exit.

  4. Run the import command by specifying the target database:

    docker exec -i mysql-container mysql -uroot -pmy-secret-pw my_database < "D:\Desktop\pms_backup.sql"
    

By adding my_database right after the password parameter, you tell the MySQL client exactly where to load the SQL commands.


2. Modify the SQL Dump File (Optional)

If you prefer that the dump file itself selects the database, you can open pms_backup.sql in a text editor and check for a line that looks like:

USE database_name;

If it’s missing, you can add a statement at the beginning of the file:

CREATE DATABASE IF NOT EXISTS my_database;
USE my_database;

Then run the original command without specifying the database in the command line:

docker exec -i mysql-container mysql -uroot -pmy-secret-pw < "D:\Desktop\pms_backup.sql"

Why the Error Occurs

Without a selected database, commands such as CREATE TABLE or INSERT INTO don’t know which database to use. Hence, you see the error message:

ERROR 1046 (3D000) at line 23: No database selected

This is MySQL’s way of informing you that it can’t associate the SQL statements with any existing database.


Summary

  • Option 1: Create the database manually in MySQL and specify it during the import.
  • Option 2: Modify your SQL dump file to include commands that create and select the appropriate database before executing the rest of the commands.

Either method will ensure that MySQL knows which database to use, and the error should be resolved.

To test the MySQL database running in the Docker container using Python, you can use the mysql-connector-python library to connect to the MySQL server and execute queries. Below is a sample Python code to test the database connection and perform some basic operations:

Prerequisites

  1. Install the mysql-connector-python library if you haven’t already:
    pip install mysql-connector-python
    

Python Code to Test the MySQL Database

import mysql.connector
from mysql.connector import Error

# Database connection parameters
host = "127.0.0.1"  # or "localhost"
port = 3306
user = "root"
password = "my-secret-pw"  # Replace with your MySQL root password
database = "my_database"  # Replace with the database name you imported data into

def test_database_connection():
    try:
        # Establish a connection to the MySQL database
        connection = mysql.connector.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=database
        )

        if connection.is_connected():
            print("Successfully connected to the MySQL database!")
            cursor = connection.cursor()

            # Example: List all tables in the database
            cursor.execute("SHOW TABLES")
            print("Tables in the database:")
            for table in cursor:
                print(table[0])

            # Example: Execute a simple query
            cursor.execute("SELECT * FROM your_table_name LIMIT 5")  # Replace with your table name
            rows = cursor.fetchall()
            print("\nSample data from the table:")
            for row in rows:
                print(row)

    except Error as e:
        print(f"Error: {e}")
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()
            print("MySQL connection is closed.")

if __name__ == "__main__":
    test_database_connection()

Explanation

  1. Database Connection Parameters:

    • host: The IP address or hostname of the MySQL server. Since the MySQL container is running on the same machine, 127.0.0.1 or localhost can be used.
    • port: The port number MySQL is running on (default is 3306).
    • user: The MySQL username (e.g., root).
    • password: The password for the MySQL user.
    • database: The name of the database you imported data into.
  2. Connecting to the Database:

    • The mysql.connector.connect() function establishes a connection to the MySQL server using the provided parameters.
  3. Executing Queries:

    • The code lists all tables in the database using the SHOW TABLES query.
    • It also executes a sample query (SELECT * FROM your_table_name LIMIT 5) to fetch and print the first 5 rows of data from a table. Replace your_table_name with the actual table name in your database.
  4. Error Handling:

    • The try-except block is used to catch and print any errors that occur during the database operations.
  5. Closing the Connection:

    • The connection is closed in the finally block to ensure proper cleanup.

Running the Code

  1. Save the code to a file, for example, test_mysql.py.
  2. Run the script using Python:
    python test_mysql.py
    
  3. If the connection is successful, you should see output listing the tables and sample data from the database.

Make sure the MySQL container is running and accessible before executing this script.

import mysql.connector
from mysql.connector import Error

Database connection parameters

host = “127.0.0.1” # or “localhost”
port = 3306
user = “root”
password = “my-secret-pw” # Replace with your MySQL root password
database = “my_database” # Replace with the database name you imported data into

def test_database_connection():
try:
# Establish a connection to the MySQL database
connection = mysql.connector.connect(
host=host,
port=port,
user=user,
password=password,
database=database
)

    if connection.is_connected():
        print("Successfully connected to the MySQL database!")
        cursor = connection.cursor()

        # Example: List all tables in the database
        cursor.execute("SHOW TABLES")
        print("Tables in the database:")
        for table in cursor:
            print(table[0])

        # Example: Execute a simple query
        cursor.execute("SELECT * FROM test_manage_bug_manage_bug_list LIMIT 5")  # Replace with your table name
        rows = cursor.fetchall()
        print("\nSample data from the table:")
        for row in rows:
            print(row)

except Error as e:
    print(f"Error: {e}")
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed.")

if name == “main”:
test_database_connection()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值