To do this, the simplest way is to use a JDBC driver :
- Downlaod the integral API from here.
- Put it in the /lib of your Tomcat installation folder if you want to use it in a web project or any folder accessible in your hard disk
- Right click on your project in Eclipse > Properties > Java Build Path > Add External JARs… > Choose the jar : mysql-connector-java-5.1.16-bin.jar from the installation folder > OK. the jar will appear in the build path. Click on OK.
- Use the following code in your method :
private static final String connectionString =”jdbc:mysql://IP_OR_NAME_SERVER;DatabaseName=DATABASE_NAME;user=USER;password=PWD“;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Person> usersList = new ArrayList();
try{ Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(connectionString);
stmt = conn.createStatement();
String sqlQuery=”YOUR_QUERY_HERE “; // You put here your query : SELCET, UPDATE, DELETE, INSERT
rs = stmt.executeQuery(sqlQuery); // If it is a SELECT QUERY e.g sqlQuery=”SELECT user,email FROM user”;
while ( rs.next() ){ // To get data from result
Person user = new Person(); user.setName(rs.getString(“user”)); user.setEmail(rs.getString(“email”));
usersList.add(user);
}
stmt.executeUpdate(sqlQuery); // If it is an UPDATE, DELETE or INSERT QUERY
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
if (rs != null) try { rs.close(); } catch (Exception e) { //LOGGER}
if (stmt != null) try { stmt.close(); } catch (Exception e) {//LOGGER }
if (conn != null) try { conn.close(); } catch (Exception e) { //LOGGER} } - Congratulation… You made a connection with your mySql database by using JAVA and JDBC.
See also :
- How to install a new tomcat server in your workspace?
- How to make a connection with a sqlServer database by using Java?
- How to make a web service by using Eclipse?
- How to create a web service SOAP?