ALEENA JOHN ALEENA JOHN - 1 year ago 139
Java Question

How can I connect to mariadb using java?

I've used:

Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "username", "password"
Statement stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE a (id int not null primary key, value varchar(20))");

but it gives an error "No route to host"

Answer Source

//STEP 1. Import required packages package mariadb;

import java.sql.*;

public class Mariadb { // JDBC driver name and database URL

static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
static final String DB_URL = "jdbc:mariadb://";

//  Database credentials
static final String USER = "root";
static final String PASS = "root";

public static void main(String[] args) {
    Connection conn = null;
    Statement stmt = null;
    try {
        //STEP 2: Register JDBC driver

        //STEP 3: Open a connection
        System.out.println("Connecting to a selected database...");
        conn = DriverManager.getConnection(
                "jdbc:mariadb://", "root", "root");
        System.out.println("Connected database successfully...");

        //STEP 4: Execute a query
        System.out.println("Creating table in given database...");
        stmt = conn.createStatement();

        String sql = "CREATE TABLE REGISTRATION "
                + "(id INTEGER not NULL, "
                + " first VARCHAR(255), "
                + " last VARCHAR(255), "
                + " age INTEGER, "
                + " PRIMARY KEY ( id ))";

        System.out.println("Created table in given database...");
    } catch (SQLException se) {
        //Handle errors for JDBC
    } catch (Exception e) {
        //Handle errors for Class.forName
    } finally {
        //finally block used to close resources
        try {
            if (stmt != null) {
        } catch (SQLException se) {
        }// do nothing
        try {
            if (conn != null) {
        } catch (SQLException se) {
        }//end finally try
    }//end try
}//end main

}//end JDBCExample

I use this example.I change the bind address to and i restart the server sudo /etc/init.d/mysql start .

List item

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download