Vinh La Kiến

43 bundles
1 file22 days ago
3

Java JDBC MySQL Example

Code mẫu kết nối đến MySQL bằng JDBC.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150package com.company;

import java.sql.*;
import java.util.Scanner;

public class Main {
    private final static boolean isProduction = false;

    private boolean createDatabase(Connection connection, String database) {
        try {
            Statement statement = connection.createStatement();
            statement.executeUpdate("CREATE DATABASE " + database);
            return true;
        } catch (Exception e) {
            System.out.println("Could not create database: " + e.toString());
            return false;
        }
    }

    private static Connection getConnection(String host, Integer port, String username, String password) {
        String connectionString = "jdbc:mysql://" + host + ":" + port.toString() + "/";
        Connection connection = null;

        try {
            return DriverManager.getConnection(connectionString + "?serverTimezone=UTC", username, password);
        }
        catch (Exception e)
        {
            System.out.println("Could not sign in.");
            System.out.println(e.toString());
            return null;
        }
    }

    private static Connection getConnectionToDatabase(String host, Integer port, String database, String username, String password) {
        String connectionString = "jdbc:mysql://" + host + ":" + port.toString() + "/" + database;
        Connection connection = null;

        try {
            return DriverManager.getConnection(connectionString + "?serverTimezone=UTC", username, password);
        }
        catch (Exception e)
        {
            System.out.println("Could not access to database.");
            System.out.println(e.toString());
            return null;
        }
    }

    public static void main(String[] args) throws SQLException {
        String host = "";
        Integer port = 0;
        String database = "";
        String username = "";
        String password = "";

        Scanner scanner = new Scanner(System.in);

        if (isProduction == false)
        {
            host = "localhost";
            port = 3306;
            database = "hotel_db";
            username = "root";
            password = "";
        }
        else
        {
            host = scanner.nextLine();
            try {
                port = Integer.getInteger(scanner.nextLine());
            }
            catch (Exception e)
            {
                System.out.println("Port must be Integer.");
                System.out.println(e.toString());
                System.exit(1);
            }
            database = scanner.nextLine();
            username = scanner.nextLine();
            password = scanner.nextLine();
        }

        Connection connection = getConnectionToDatabase(host, port, database, username, password);

        if (connection == null){
            System.out.println("Could not connect to database. Exit with error code 2.");
            System.exit(2);
        }
        else
        {
            System.out.println("Connected to database.");
            boolean isExit = false;

            while(isExit == false)
            {
                System.out.println(">");
                String command = scanner.nextLine();

                if (command.compareTo("exit") == 0)
                {
                    isExit = true;
                    connection.close();
                }
                else
                {
                    Statement queryStatement = connection.createStatement();

                    if (command.toLowerCase().indexOf("select") == 0)
                    {
                        ResultSet results = queryStatement.executeQuery(command);
                        while(results.next()) {
                            System.out.println(results.getInt("id") + " " + results.getString("firstName") + "  " + results.getString(3) + " " + results.getString(5));
                        }
                    }
                    else
                    {
                        queryStatement.executeUpdate(command);
                    }
                }
            }
        }

        /*
        if (connection != null)
        {
            Statement queryStatement = connection.createStatement();
            ResultSet results = queryStatement.executeQuery("SELECT * FROM customer");

            while(results.next()) {
                System.out.println(results.getInt("id") + " " + results.getString("firstName") + "  " + results.getString(3) + " " + results.getString(5));
            }

            Statement updateStatment = connection.createStatement();
            // updateStatment.executeUpdate("DELETE FROM customer WHERE firstName='Trang'");

            updateStatment.executeUpdate(
                    "INSERT INTO `customer` (`firstName`, `lastName`, `phone`, `email`, `password`) VALUES ('Van', 'abc', '333', '@yahoo.vn', '444');",
                    Statement.RETURN_GENERATED_KEYS);

            ResultSet generatedKeys = updateStatment.getGeneratedKeys();
            if (generatedKeys.next()) {
                System.out.println(generatedKeys.getInt(1));
            }

            connection.close();
        }
        */
    }
}