Last active
March 12, 2017 19:41
-
-
Save salekh/433bc451bdc47d84f3810e823aa34707 to your computer and use it in GitHub Desktop.
Connecting to MySQL Database from Java
This file contains 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 base; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.SQLException; | |
/** | |
* Created by sanchitalekh on 12/03/2017. | |
*/ | |
public class DBConnection { | |
Connection conn; | |
String server; | |
String port; | |
String dbname; | |
String username; | |
String password; | |
public DBConnection(String server, String port, String dbname, String username, String password){ | |
this.server = server; | |
this.port = port; | |
this.dbname = dbname; | |
this.username = username; | |
this.password = password; | |
} | |
public Connection establishConnection(){ | |
try { | |
Connection conn = | |
DriverManager.getConnection("jdbc:mysql://" + this.server + ":" + this.port + "/" + this.dbname + "?" + | |
"user=" + this.username + "&password=" + this.password); | |
if(conn != null){ | |
System.out.println("Connection to " + server + " established"); | |
return conn; | |
} | |
} | |
catch (SQLException ex) { | |
ex.printStackTrace(); | |
} | |
return conn; | |
} | |
public static void main(String[] args) { | |
Connection conn; | |
DBConnection db = new DBConnection("localhost","8889","test","test","test"); | |
conn = db.establishConnection(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this code so many times, it was only fair to finally do this!