Как я могу закрыть соединение с базой данных в этом подходе? - PullRequest
1 голос
/ 02 мая 2019

Итак, я создавал программу JDBC CRUD с использованием Java Eclipse, и для предотвращения утечки данных я не могу определить, когда и как закрыть соединение.В другом случае я хотел бы спросить, открывает ли моя программа соединение при каждой функции, что делает его менее желательным.Ниже приведен мой код:

_getConnection code устанавливает соединение с базой данных,

package com.Database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class _getConnection {

    static final String JDBC_Driver = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://localhost:3306/rubyrail?useSSL=false";
    static final String Username = "root";
    static final String Password = "root";
    static Connection connection = null;


    public Connection connect()
    {
        //Connection connection = null;

        try {
              Class.forName("com.mysql.jdbc.Driver");              
              connection = DriverManager.getConnection(URL, Username, Password); 
        }
        catch(Exception e)
        {}

        return connection;
    }

    public static Connection close()
    {
        if (connection!=null)
        {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return connection;
    }
}

Database_Connection является приложением CRUD,

package com.Database;

import java.sql.*;
import java.sql.Date;
import java.util.*;

public class Database_Connection
{
    static Scanner scanner = new Scanner(System.in);

    public static void Create()
    {
        _getConnection get_connect = new _getConnection();
        Connection conn = get_connect.connect();
        int item_no = 0;
        String item_name = null;
        int item_cost = 0;
        Statement stmt = null;
        System.out.println("\nEnter the following details,");
        System.out.println("\nItem Number: ");
        item_no = scanner.nextInt();
        scanner.nextLine();
        System.out.println("\nItem Name: ");
        item_name = scanner.nextLine();
        System.out.println("\nItem Cost: ");
        item_cost = scanner.nextInt();

        try 
        {
            String sql = "Insert into item (item_no, item_name, item_cost, last_update) values ("+item_no+",'"+item_name+"',"+item_cost+",CURDATE())";
            stmt = conn.prepareStatement(sql);
            stmt.executeUpdate(sql);
            //stmt.execute(sql);
        }
        catch(Exception e)
        {System.out.println(e);}


    }

    public static void Read()
    {
        _getConnection get_connect = new _getConnection();
        Connection conn = get_connect.connect();
        Statement stmt=null;

        try 
        {
            String sql = "Select * from item";
            stmt = conn.prepareStatement(sql);
            ResultSet resultset = stmt.executeQuery(sql);
            while (resultset.next())
            {
                int item_no = resultset.getInt("item_no");
                String item_name = resultset.getString("item_name");
                int item_cost = resultset.getInt("item_cost");
                Date last_update = resultset.getDate("last_update");

                System.out.print("Item Number: " + item_no);
                 System.out.print(", Item Name: " + item_name);
                 System.out.print(", Item Cost: " + item_cost);
                 System.out.println(", Last Updated: " + last_update);
            }
        }
        catch(Exception e)
        {System.out.println(e);}
    }

    public static void Update()
    {
        _getConnection get_connect = new _getConnection();
        Connection conn = get_connect.connect();
        Statement stmt=null;
        int item_no = 0;
        String item_name = null;
        int item_cost = 0;
        System.out.println("\nEnter the Item Number to be Updated,");
        System.out.println("\nItem Number: ");
        item_no = scanner.nextInt();
        scanner.nextLine();
        System.out.println("\nEnter the following details,");
        System.out.println("\nItem Name: ");
        item_name = scanner.nextLine();
        System.out.println("\nItem Cost: ");
        item_cost = scanner.nextInt();

        try 
        {
            String sql = "update item set item_name = '"+item_name+"',item_cost ="+item_cost+",last_update = CURDATE() where item_no = "+item_no;
            stmt = conn.prepareStatement(sql);
            stmt.executeUpdate(sql);
        }
        catch(Exception e)
        {System.out.println(e);}

    }

    public static void Delete()
    {
        _getConnection get_connect = new _getConnection();
        Connection conn = get_connect.connect();
        Statement stmt=null;
        int item_no = 0;
        System.out.println("\nEnter the Item Number to be Deleted,");
        System.out.println("\nItem Number: ");
        item_no = scanner.nextInt();

        try 
        {
            String sql = "delete from item where item_no = "+item_no;
            stmt = conn.prepareStatement(sql);
            stmt.executeUpdate(sql);
        }
        catch(Exception e)
        {System.out.println(e);}
    }

    public static void Close()
    {
        _getConnection.close();

        System.out.println("Closing Connection..");

        System.out.println("Connection Closed!");
    }

        public static void main (String args[])
        {
            _getConnection get_connect = new _getConnection();
            Connection conn = get_connect.connect();
            int choice= 0;
            try {
                  if(conn!=null)
                  while (choice < 6)
                  {
                      System.out.println("\n1. Create");
                      System.out.println("\n2. Read");
                      System.out.println("\n3. Update");
                      System.out.println("\n4. Delete");
                      System.out.println("\n5. Close");

                  choice = scanner.nextInt();
                  switch(choice)
                  {
                  case 1: Create();
                  break;

                  case 2: Read();
                  break;

                  case 3: Update();
                  break;

                  case 4: Delete();
                  break;

                  case 5: Close();
                  break;
                  }
                } 
            }
            catch (Exception e) {}
        }

}

Я бы хотел, чтобы мое решение имелозакрытие в функции Close () программы.

Ответы [ 2 ]

0 голосов
/ 02 мая 2019

Вы можете изменить свой код на что-то вроде:

public class DatabaseConnection {

    static final String URL = "jdbc:mysql://localhost:3306/rubyrail?useSSL=false";
    static final String Username = "root";
    static final String Password = "root";

    private static Connection createConnection() {
        return DriverManager.getConnection(URL, Username, Password);
    }

    public static void create() {
        try (Connection connection = createConnection()) {
            // do something with the connection
        } catch (SQLException e) {
            e.printStackTrace();
            // or something else to handle the error
        }
    }

    // same for the rest of your methods

    public static void main (String args[]) {
        int choice= 0;
        while (choice < 6) {
            System.out.println("\n1. Create");
            System.out.println("\n2. Read");
            System.out.println("\n3. Update");
            System.out.println("\n4. Delete");
            System.out.println("\n5. Close");

            choice = scanner.nextInt();
            switch(choice) {
            case 1: 
                create();
                break;
            // other cases
            }
        }
    }
}

Это создаст соединение для каждого вызова метода, что может быть менее эффективным, но упростит управление ресурсами.Если производительность действительно важна, вам следует рассмотреть возможность использования источника данных, который обеспечивает пул соединений (например, HikariCP, Apache DBCP и т. Д.).Использование пула соединений позволит повторно использовать соединения без необходимости беспокоиться об этом, кроме настройки конфигурации источника данных.

В качестве альтернативы, создайте соединение один раз в главном и передайте его каждому методу, который вы хотитеЗвоните:

public static void create(Connection connection) {
    try {
        // do something with connection
    } catch (SQLException e) {
        e.printStackTrace();
        // or something else to handle the error
    }
}
public static void main (String args[]) {
    try (Connection connection = createConnection()) {
        int choice= 0;
        while (choice < 6) {
            System.out.println("\n1. Create");
            System.out.println("\n2. Read");
            System.out.println("\n3. Update");
            System.out.println("\n4. Delete");
            System.out.println("\n5. Close");

            choice = scanner.nextInt();
            switch(choice) {
            case 1: 
                create(connection);
                break;
            // other cases
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        // or something else to handle the error
    }
}
0 голосов
/ 02 мая 2019

Всегда рекомендуется закрывать соединение с базой данных. Вы можете добавить блок finally, чтобы закрыть соединение с базой данных. Рекомендуется закрывать соединения в следующем порядке. ResultSet, Statement, and Connection в блоке finally в конце вашей программы.

Пожалуйста, перейдите по этой ссылке для более подробной информации [Принято ответ] https://stackoverflow.com/a/2225275/7719903

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...