LearnFast.Ninja

Java jdbc example mysql

How to connect to MySQL using jdbc. The function in this example return User object form the database. We are using ResultSet then we fill the User instance.

Working example code:

public static User Get_User_By_ID(String ID) {

       User oUser = null;

       try {

              Class.forName("com.mysql.jdbc.Driver");

              Connection oConnection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/DatabaseName", "UserName","Password"); //?useUnicode=yes&characterEncoding=UTF-8

              try {

                     Statement oStatement = oConnection.createStatement();

                     ResultSet oResultSet = oStatement.executeQuery("SELECT User_ID, User_Name FROM Users WHERE User_ID = " + ID);

                    

                     while (oResultSet.next()) {

                           String User_ID = oResultSet.getString("User_ID");

                           String User_Name = oResultSet.getString("User_Name");

                           oUser = User_Builder.Create_User_By_ID_And_Name(User_ID, User_Name);

                     }

                     oStatement.close();

              } finally {

                     oConnection.close();

              }

       } catch (Exception e) {

              e.printStackTrace();

       }

       return oUser;

}


Tags

java

mysql jdbc resultset connection