# Connect to MySQL server inside a docker from vscode

Useful links

[https://hub.docker.com/r/mysql/mysql-server/](https://hub.docker.com/r/mysql/mysql-server/)

[https://docs.docker.com/network/](https://docs.docker.com/network/)

[MySQL - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=formulahendry.vscode-mysql)

### Download and run a MySQL Server Docker Image

```bash
docker pull mysql/mysql-server
docker run --name=mysql1 -p 3306:3306 -d mysql/mysql-server
```

Check logs to see the generated root password (look for GENERATED ROOT PASSWORD)

```bash
docker logs mysql1
```

Connect to the running server as root user and then create a new user for localhost

```bash
mysql -u root -p

CREATE USER 'sqluser'@'%' IDENTIFIED 
WITH mysql_native_password BY 'password' ; 

GRANT ALL PRIVILEGES ON *.* TO 'sqluser'@'%' ;

FLUSH PRIVILEGES;
```

Now mysql server is ready to be connected from host machine. I used an extension called '[**MySQL**](https://marketplace.visualstudio.com/items?itemName=formulahendry.vscode-mysql) **by** [**Jun Han**](https://marketplace.visualstudio.com/publishers/formulahendry)' in vscode

* To add MySQL connection: in Explorer of VS Code, click "MYSQL" in the bottom left corner, then click the `+` button, then type host, user, password, port and certificate file path (optional) in the input box.
    
* To run MySQL query, open a SQL file first then:
    
    * right click on the SQL file, then click `Run MySQL Query` in editor context menu (Note: you could also run the selected SQL query)
        
    * or use shortcut `Ctrl+Alt+E`
        
    * or press `F1` and then select/type `Run MySQL Query`
