Here we will learn to connect to MYSQL DB via Java.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Scanner;
/*
* Here we will learn to connect to Oracle DB using JDBC Driver.
*/
public class ConnectMySQLDB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out
.println("Please provide below details to connect MySQL Database");
System.out.println("Enter Database");
String dbName = scanner.next();
System.out.println("Enter UserName");
String userName = scanner.next();
System.out.println("Enter Password");
String password = scanner.next();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/" + dbName,
userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("nSuccessfullly connected to MySQL DB");
} else {
System.out.println("nFailed to connect to MySQL DB");
}
}
}
JARs Required :
mysql-connector-java-5.1.22-bin.jar(Download Here)
Tools Used :
Eclipse Indigo
Java Version
JDK 1.6
this is just connect and disconnect. how about do select?