Is there a standard way to connect a Java program to a MySQL database, and which is the easiest one?
Asked
Active
Viewed 599 times
4 Answers
0
JDBC is the standard way. Below is the sample java code to connect MySQL database:
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String db = "testdb";
String dbUser = "root";
String dbPasswd = "mysql123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "DELETE FROM user WHERE email = 'riponalwasim@gmail.com'";
int delete = st.executeUpdate(sql);
if(delete >= 1){
System.out.println("Row is deleted.");
}
else{
System.out.println("Row is not deleted.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}

Ripon Al Wasim
- 36,924
- 42
- 155
- 176
0
In addition to answer posted above, JPA (Hibernate) is even easier one once you cross the initial barrier called learning curve (and before you are hit by next one called, Performance Optimization). On the serious note, Yes JPA is also a standard way to connect and query pretty much any database the same way.

kdabir
- 9,623
- 3
- 43
- 45