Skip to content

Instantly share code, notes, and snippets.

@sumukus
Last active May 19, 2020 16:26
Show Gist options
  • Save sumukus/568983ab7bce7fc1066001af9c18c613 to your computer and use it in GitHub Desktop.
Save sumukus/568983ab7bce7fc1066001af9c18c613 to your computer and use it in GitHub Desktop.
It is a java program code to connect to MariaDB database in Ubuntu Operating system using the Connector/J JDBC
import java.sql.*;
public class ConnectionDemo {
public static void main(String[] arg){
//Declaring the variables
Connection con = null;
Statement stm = null;
ResultSet rs = null;
try{
//Connecting to the mariadb databse
//database:test, user:root, password:root
con = DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/test?user=root&password=root"
);
//Creating the sql query statements to select all the records from the user table
stm = con.createStatement();
rs = stm.executeQuery("SELECT * FROM user");
//Accessing the record from one-by-one and printing it
if(rs != null){
int i=1;
while(rs.next()){
System.out.println(
"\t\tRecord "+i+
"\nName:"+rs.getString("name")+
"\nAge:"+rs.getString("age") +
"\nGender:"+rs.getString("gender")
);
i++;
}
//In case if the user table is empty
}else{
System.out.println("User Table is Empty");
}
//Throwing the catch statement in case the connection is not established
}catch(SQLException sqlEx){sqlEx.printStackTrace();}
finally{
//Releasing the ResultSet once it is no more required and assign it null value
if(rs != null){
try{
rs.close();
}catch(SQLException sqlEx){sqlEx.printStackTrace();}
rs = null;
}
//Releasing the createStatement once it is no more required and assign it null value
if(stm != null){
try{
stm.close();
}catch(SQLException sqlEx){sqlEx.printStackTrace();}
stm = null;
}
//Finally closing the database connection
try{
con.close();
}catch(Exception e){e.printStackTrace();}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment