Setting up MySQL for Vibe.d

We will try to separate the database access code from the business logic so we can roughly follow the model-view-controller paradigm.

To use MySQL in a Vibe.d app, we need to add an external library to our project, in this case, mysql-native (I wanted to use DDBC but DDBC doesn’t work on my Windows machine).

Create a new project named lorem.

C:\vibeprojects\empapp>cd .. 
C:\vibeprojects>dub init lorem -t vibe.d
...
C:\vibeprojects>cd lorem
C:\vibeprojects\lorem>

The easy, convenient and proper way to add the mysql-native library is to use dub.

Here is the present state of dub.json:

{
  "authors": [
    "Owner"
  ],
  "copyright": "Copyright © 2023, Owner",
  "dependencies": {
    "vibe-d": "~>0.9"
  },
  "description": "A simple vibe.d server application.",
  "license": "proprietary",
  "name": "empapp"
}

To add an external library or dependency, we type dub add

c:\vibeprojects\empapp>dub add mysql-native
             Adding dependency mysql-native ~>3.2.0

And here is the dub.json file after we added mysql-native:

{
  "authors": [
    "Owner"
  ],
  "copyright": "Copyright © 2023, Owner",
  "dependencies": {
   "mysql-native": "~>3.2.0",
    "vibe-d": "~>0.9"
  },
  "description": "A simple vibe.d server application.",
  "license": "proprietary",
  "name": "empapp"
}

Now we are ready to use MySQL in our project.

Let’s review source\app.d:

import vibe.vibe;
import empcontrol;
void main()
{
  auto settings = new HTTPServerSettings;
  settings.port = 8080;
  settings.bindAddresses = ["::1", "127.0.0.1"];
  auto router = new URLRouter;
  router.get("*", serveStaticFiles("public/"));
  router.registerWebInterface(new EmployeeController);
  auto listener = listenHTTP(settings, router);
  scope (exit) listener.stopListening();
 
  runApplication();
}

Here we indicated that we are instantiating the EmployeeController class.

Last updated