Created
October 23, 2017 20:57
-
-
Save jsbonso/3478e9e08bd0e62a8229ec8bd52692dd to your computer and use it in GitHub Desktop.
How to connect Java to MySQL Database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.tutorialsdojo; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
import java.sql.ResultSetMetaData; | |
/** | |
* How to connect to a mySQL Database. | |
* | |
* @author Jon Bonso | |
* | |
*/ | |
public class DatabaseConnection { | |
public static void main(String[] args) { | |
try { | |
connectToDB(); | |
}catch (Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* Connect to MySQL Database | |
* @throws SQLException | |
*/ | |
private static void connectToDB() throws SQLException{ | |
// 1. Get the Connection instance using the DriverManager.getConnection() method | |
// with your MySQL Database Credentails | |
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tutorialsdojo", | |
"tutorialsdojo", "P@sSword123"); | |
System.out.println("LOG: Connection Established!"); | |
// 2. Execute your SQL Query using conn.createStatement.executeQuery() | |
// and get the result as a ResultSet object. | |
// with your MySQL Database Credentails | |
ResultSet rs = conn.createStatement().executeQuery("select now()"); | |
ResultSetMetaData rsmd = rs.getMetaData(); | |
System.out.println("Query Results: \n\n"); | |
// Show Column Names | |
getColumnNames(rsmd); | |
// Getting the Results | |
while (rs.next()){ | |
for ( int i=1; i <= rsmd.getColumnCount(); i++){; | |
System.out.print(rs.getString(i) + "\t\t"); | |
} | |
System.out.println(); | |
} | |
} | |
/** | |
* Shows the Column Names | |
* @param rs | |
* @throws SQLException | |
*/ | |
private static void getColumnNames(ResultSetMetaData rsmd) throws SQLException{ | |
// Getting the list of COLUMN Names | |
for ( int i=1; i <= rsmd.getColumnCount(); i++){ | |
System.out.print(rsmd.getColumnName(i) + "\t\t|"); | |
} | |
System.out.println(""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have done successfully