【问题标题】:Do we need to establish JDBC connectivity every time the server needs to query the database? [duplicate]每次服务器需要查询数据库时,我们是否需要建立JDBC连接? [复制]
【发布时间】:2022-01-10 00:50:56
【问题描述】:

我在 Java 中有一个客户端-服务器-数据库设置,我正在想办法一起设置服务器代码和数据库连接代码,我有以下 2 个类(我们所说的未连接):

连接数据库并执行随机查询的类:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseConnection {

    public static void main(String[] args) {

        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }

        Connection conn = null;

        try {
            conn =
               DriverManager.getConnection("jdbc:mysql://localhost:3306/test" +
                                           "?user=root&password=test");


          
        } catch (SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        
       
        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM Authentication");

            // or alternatively, if you don't know ahead of time that
            // the query will be a SELECT...

            if (stmt.execute("SELECT * FROM Authentication")) {
                rs = stmt.getResultSet();
            }
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnsNumber = rsmd.getColumnCount(); 
            while (rs.next()) {
                for (int i = 1; i <= columnsNumber; i++) {
                    if (i > 1) System.out.print(" ");
                    String columnValue = rs.getString(i);
                    System.out.print(columnValue );
                }
                System.out.println("");
            }
            
        }
        catch (SQLException ex){
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
        finally {
            // it is a good idea to release
            // resources in a finally{} block
            // in reverse-order of their creation
            // if they are no-longer needed

            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException sqlEx) { } // ignore

                rs = null;
            }

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException sqlEx) { } // ignore

                stmt = null;
            }
        }
        
    }

}

服务器类:

import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;

public class MultipleServer {
    public static void main(String[] args) throws IOException {
        Scanner scan=new Scanner(System.in);
        
        System.out.println("Enter the port number on which the server should be listening on");
        int portnum=scan.nextInt();
        ServerSocket serverSocket = new ServerSocket(portnum);

        // Server keeps on receiving new Clients
        while (true) {
            Socket clientSocket = null;
            try {
                // ServerSocket waits for a Client to connect
                clientSocket = serverSocket.accept();

                System.out.println("A new client is connected : " + clientSocket);

                // Receiving input and sending output to Client
                DataInputStream inputFromClient = new DataInputStream(clientSocket.getInputStream());
                DataOutputStream outputToClient = new DataOutputStream(clientSocket.getOutputStream());

                System.out.println("Assigning new thread for this client");

                System.out.println("-----------------------------------------------------------------------------------");

                // Create a new Thread object for the Client
                Thread thread = new ClientHandler(clientSocket, inputFromClient, outputToClient);
                thread.start();

            } catch (Exception e) {
                clientSocket.close();
                e.printStackTrace();
            }
        }
    }
}

// ClientHandler class
class ClientHandler extends Thread {
    final Socket clientSocket;
    final DataInputStream inputFromClient;
    final DataOutputStream outputToClient;

    // Constructor
    public ClientHandler(Socket clientSocket, DataInputStream inputFromClient, DataOutputStream outputToClient) {
        this.clientSocket = clientSocket;
        this.inputFromClient = inputFromClient;
        this.outputToClient = outputToClient;
    }

    @Override
    public void run() {
        // Variables
        String received;
        String toreturn;
        while (true) {
            try {
                // Initiate communication with Client
                outputToClient.writeUTF("Type Exit to terminate connection.");

                // Receive the answer from Client
                received = inputFromClient.readUTF();

                // Receiving Exit closes the connection and breaks the loop
                if (received.equals("Exit")) {
                    System.out.println("-----------------------------------------------------------------------------------");
                    System.out.println("Client " + this.clientSocket + " sends exit...");
                    System.out.println("Closing this connection.");
                    this.clientSocket.close();
                    System.out.println("Connection closed");
                    break;
                }

                // Send to Client what is requested
                switch (received) {

                default:
                    outputToClient.writeUTF("Invalid input");
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            // Closing resources
            this.inputFromClient.close();
            this.outputToClient.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我有几个查询需要执行,我的想法是将每个查询放在一个单独的方法中,并在将所需的输入作为参数的同时从客户端调用它,但是,如果我这样做,则连接成功'没有建立,因为它将在main() 中,所以我是否只在每个方法中包含将我的程序连接到服务器的代码?还是我只是将其合并到一个类中?

【问题讨论】:

  • 您熟悉数据库连接池吗?您显然没有在 JEE 环境中运行,但像 c3p0 这样的工具可以提供帮助。
  • 您在学习过时的旧教程吗?您的代码看起来很笨拙,例如不使用 try-with-resources 和其他类似的东西。我建议你看看像Baeldung这样的可靠来源。
  • @Kayaman 这主要来自 MySQL 官网
  • @studnbar 不,我不是
  • @Sergio 真的吗?我想他们不会经常更新它。好像是业余爱好者写的。

标签: java mysql jdbc


【解决方案1】:

不,您不需要新的连接。您可以多次重复使用同一个连接。

【讨论】:

  • 那么建立连接的代码在哪里呢?
  • 如果我把它放在main中,我认为当我调用main以外的方法时它不会被简单地执行(如果我错了请纠正我),并且客户端可以决定调用任何方法,所以我不能把它放在某个知道它是第一个被调用的方法中
  • 通常人们使用连接池。它将为您处理打开和关闭连接的库。
猜你喜欢
  • 2011-04-07
  • 2014-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多