Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.*;
- import java.util.Scanner;
- public class Main {
- static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mysql";
- static final String DB_USER = "root";
- static final String DB_PASSWORD = "password";
- private static void addFlat(Connection conn, String district, String address, float area, int rooms, float price) throws SQLException {
- try (PreparedStatement ps = conn.prepareStatement("INSERT INTO Flats (district, address, area, rooms, price) " +
- "VALUES(?, ?, ?, ?, ?)")) {
- ps.setString(1, district);
- ps.setString(2, address);
- ps.setFloat(3, area);
- ps.setInt(4, rooms);
- ps.setFloat(5, price);
- ps.executeUpdate();
- }
- }
- private static void initDB(Connection conn) throws SQLException {
- try (Statement st = conn.createStatement()) {
- st.execute("DROP TABLE IF EXISTS Flats");
- st.execute("CREATE TABLE Flats (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " +
- "district VARCHAR(50) NOT NULL, " +
- "address VARCHAR(100) NOT NULL, " +
- "area FLOAT NOT NULL, " +
- "rooms TINYINT NOT NULL, " +
- "price FLOAT NOT NULL)");
- }
- addFlat(conn, "Печерський", "вул. Хрещатик 0.5", 1, 1, 999999);
- addFlat(conn, "Броварський", "вул. Шевченка 10", 20.2f, 3, 0.5f);
- addFlat(conn, "Печерський", "вул. Кутузова 12", 5, 2, 100);
- addFlat(conn, "Дарницький", "вул. Ялинкова 320", 100, 10, 0.1f);
- addFlat(conn, "Дарницький", "вул. Зарічна 10Я", 2, 30, 200);
- addFlat(conn, "Святошинський", "вул. Верховинна 23", 10, 5, 54.5f);
- addFlat(conn, "Святошинський", "вул. Генерала Наумова 42", 7.5f, 3, 23.15f);
- }
- public static void view(Connection conn,String query) throws SQLException {
- String s = "";
- if (!query.isEmpty()) s = " WHERE " + query;
- try (PreparedStatement ps = conn.prepareStatement("SELECT * FROM Flats" + s)) {
- try (ResultSet rs = ps.executeQuery()) {
- ResultSetMetaData md = rs.getMetaData();
- System.out.print("(");
- for (int i = 1; i <= md.getColumnCount(); i++) {
- System.out.print(md.getColumnName(i));
- if (i != md.getColumnCount())
- System.out.print("; ");
- }
- System.out.println(")");
- while (rs.next()) {
- System.out.print("(");
- for (int i = 1; i <= md.getColumnCount(); i++) {
- System.out.print(rs.getString(i));
- if (i != md.getColumnCount())
- System.out.print("; ");
- }
- System.out.println(")");
- }
- }
- }
- }
- public static void main(String[] args) {
- try (Scanner sc = new Scanner(System.in)) {
- try (Connection conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD)) {
- initDB(conn);
- while (true) {
- System.out.println("Write stuff");
- String query = sc.nextLine();
- if (query.equals("exit")) return;
- view(conn, query);
- }
- }
- } catch (SQLException ex) {
- ex.printStackTrace();
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement