Skip to content

Instantly share code, notes, and snippets.

@jcavat
Created April 9, 2019 08:23
Show Gist options
  • Save jcavat/669f304bc0cc257c27181ae4671d16f5 to your computer and use it in GitHub Desktop.
Save jcavat/669f304bc0cc257c27181ae4671d16f5 to your computer and use it in GitHub Desktop.
Try with resources with jdbc
import java.sql.*;
public class App {
// JDBC driver name and database URL
static final String driver = "com.mysql.cj.jdbc.Driver";
static final String dbUrl = "jdbc:mysql://ip_address:3306/databasename";
// Database credentials
static final String user = "user";
static final String pass = "pass";
public static void main(String[] args) throws ClassNotFoundException {
Class.forName(driver);
try (Connection con = DriverManager.getConnection(dbUrl, user, pass);
PreparedStatement ps = con.prepareStatement("SELECT * FROM Conference;");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String price = rs.getString("price");
System.out.println(id + ": " + name + ", " + price);
}
System.out.println("Goodbye");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment