-How to connect Java application and database when creating Java application with Eclipse installed on Mac
・ Experience in creating web applications with Rails ・ No experience in creating web applications from scratch with Java
When creating a Rails app, for example
DB configuration command in Rails
rails model User name:String email:String
rails:db mingrate
You can connect automatically by executing.
In contrast, Java apps require you to configure each one yourself.
This time, I wrote this article to study the setting.
Remarks | ||
---|---|---|
PC | MacBook Air | |
OS | MacOS Mojave | Version: 10.14.4 |
language | Java | Version: 12.0.1 |
IDE | Eclipse | Eclipse IDE for Enterprise Java Developers. Version: 2019-03 (4.11.0) |
WEB server | Apache Tomcat | Version: 8 |
DB | PostgreSQL | Version: 11.2 |
DB management tool | pgAdmin | Version: 4.5 |
browser | Chrome | version: 73.0.3683.103 |
Prepare "User" table in database "sample" The following data is stored in the "User" table
SQL
SELECT * FROM USER;
SQL execution result on pgAdmin
Place "Sampleapp6.java" to write database connection process in dynamic WEB project "sample"
Sampleapp6.java
package jp.co.sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Sampleapp6 {
public static void main(String[] args) throws Exception {
String url = "jdbc:postgresql://localhost:5432/sample";
String user = "sample database user";
String password = "samle database password";
//Connect to database
try(Connection conn = DriverManager.getConnection(url,user,password)) {
//Prepare a SELECT statement
String sql = "SELECT * FROM CUSTOMER";
PreparedStatement pStmt = conn.prepareStatement(sql);
ResultSet rs = pStmt.executeQuery();
//View results
while (rs.next()) {
String id = rs.getString("ID");
String name = rs.getString("NAME");
String email = rs.getString("EMAIL");
System.out.println(id + " " + name + " " + email);
}
} catch (SQLException e) {
e.printStackTrace();
}
};
** Apply JDBC driver **
Download the JDBC driver and save it (this time save it to your desktop) https://jdbc.postgresql.org/download.html
Right-click on the "sample" project → select "Properties"
Select "Java Build Path" → Apply the external build path saved on the desktop to "Module path"
The image below is the Eclipse console I was able to confirm that I was getting the data from the database.
In Rails, connecting a database is just a few lines of command. You have to configure all Java yourself.
I researched the DB connection method on the net, but I didn't know which information was correct and felt that it was difficult for me to study by myself.
How to implement data save / edit / update / delete process in Java application
Daigo Kunimoto "Introduction to Servlet & JSP 2nd Edition", Impress Corporation, 2019/03/21 First Edition
Recommended Posts