I am trying to connect to a mysql database using the following code.
import ballerina/io;
// import ballerina/http;
import ballerinax/mysql;
import ballerina/sql;
configurable string dbHost = ?;
configurable int dbPort = ?;
configurable string dbUser = ?;
configurable string dbPassword = ?;
configurable string dbName = ?;
type User record {
int userId;
string email;
string password;
string createdAt;
string updatedAt;
};
mysql:Client|sql:Error dbClientResult = check new (
user = dbUser,
password = dbPassword,
database = dbName,
host = dbHost,
port = dbPort
);
final mysql:Client dbClient = check dbClientResult;
public function main() returns error? {
io:println("MySQL Connected to " + dbName);
return;
}
isolated function insertUser(mysql:Client dbClient, User entry) returns sql:ExecutionResult|error {
User {userId, email, password, createdAt, updatedAt} = entry;
sql:ParameterizedQuery insertQuery = `INSERT INTO users (id, email, password, createdAt, updatedAt)
VALUES (${userId}, ${email}, ${password}, ${createdAt}, ${updatedAt})`;
return dbClient->execute(insertQuery);
}
But encounters the below error
error: Error while loading database driver. This may be because the database driver path is not configured correctly in the `Ballerina.toml` file or provided database driver version is not supported by the connector
I've added the mysql-connector-java-8.0.26.jar file and configured in the Ballerina.toml file
[mysql]
driverPath = "libs\\mysql-connector-java-8.0.26.jar"
Versions
The easiest way to add MySQL driver as a dependency to the Ballerina project is to add the following import statement at the top of the bal file.
import ballerinax/mysql.driver as _;
It will bundle the latest MySQL driver JAR. No need to configure the Ballerina.toml.
However, if you want to add a MySQL driver of a specific version, you can add it as a dependency in Ballerina.toml. Follow one of the following ways to add the JAR in the file: (Ref: https://central.ballerina.io/ballerinax/mysql/latest)
[[platform.java17.dependency]]
path = "PATH"
[[platform.java17.dependency]]
groupId = "mysql"
artifactId = "mysql-connector-java"
version = "8.0.20"
Using
[mysql]
driverPath ="PATH"
is wrong!.