import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JavaMysqlConnection{
public static void main(String[] args){
Connection connection = null;
Statement statement = null;
String sql = null;
ResultSet resultSet = null;
String user = "root";
String password = "root";
String url = "jdbc:mysql://localhost/test";
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
System.out.println("mysql driver is not ready ...");
e.printStackTrace();
}
try{
connection = DriverManager.getConnection(url,user,password);
}catch(SQLException e){
System.out.println("there is sql exception when connecting ...");
e.printStackTrace();
}
try{
statement = connection.createStatement();
sql = "select * from test";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
System.out.println("id:"+resultSet.getInt("id")+"\tname:"+resultSet.getString("name")+"\tage:"+resultSet.getInt("age")+"\tdescription:"+resultSet.getString("description"));
}
}catch(SQLException e){
System.out.println("there is sql exception ...");
e.printStackTrace();
}
try{
if(resultSet!=null){
resultSet.close();
resultSet = null;
}
if(statement!=null){
statement.close();
statement = null;
}
if(connection!=null){
connection.close();
connection = null;
}
}catch(Exception e){
System.out.println("something was wrong when closing the connection to mysql ...");
e.printStackTrace();
}
System.out.println("java connection to mysql is ending...");
}
}