Reputation: 11
I'm trying to connect to MySQL using the following JAVA code. However, I'm getting an SQLException (connection cannot be established)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
class Jdbctest {
public static void main(final String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
// for establishing connection, cnn is object of connection
final Connection cnn = DriverManager.getConnection("jdbc:oracle:thin:@//192.68.11.128:1521/orcl");
System.out.println("connection to db");
} catch (final ClassNotFoundException e) {
System.out.println(e);
} catch (final SQLException e) {
System.out.println(e);
}
}
}
Upvotes: 1
Views: 51
Reputation: 2817
This class will help you connect to mysql database. You have to change the database name and if your user is root and password is null then you good to go, else you have to change them also .
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class jdbcConnect {
public static void main (String args[]) throws SQLException{
Connection connection = null ;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabasename","root","");
JOptionPane.showMessageDialog(null, "We are Connected");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Upvotes: 0
Reputation: 114
Change
Class.forName("oracle.jdbc.driver.OracleDriver");
To this
Class.forName("com.mysql.jdbc.Driver");
And this
Connection cnn =DriverManager.getConnection("jdbc:oracle:thin:@//192.68.11.128:1521/orcl");
To this
Connection cnn =
DriverManager.getConnection("jdbc:mysql:thin:@//192.68.11.128:1521/orcl", "Enter your database username", "Enter your database password");
This is all assumming of course your database is MySQL like you said above
Upvotes: 0
Reputation: 5649
You are providing the driver class and connection string of oracle database.
How can you connect with MySQL db.
Use the below tutorial for connecting with MySQL:- http://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/
Upvotes: 3