【发布时间】: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() 中,所以我是否只在每个方法中包含将我的程序连接到服务器的代码?还是我只是将其合并到一个类中?
【问题讨论】: