Подключение MySQL к клиентскому/серверному приложению Java

Я должен разрешить клиенту выполнять запросы для моего проекта, но я не знаю, как подключить приложение Client/Server к MySQL. Я знаю только, как подключиться к MySQL в отдельном классе. Какие-либо предложения?

Сервер:

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

private ServerSocket serverSocket;
private int port;

public Server(int port) {
 this.port = port;
}

public void start() throws IOException {
 System.out.println("Starting the socket server at port:" + port);
 serverSocket = new ServerSocket(port);

 //Listen for clients. Block till one connects

 System.out.println("Waiting for clients...");
 Socket client = serverSocket.accept();

 //A client has connected to this server. Send welcome message
 sendWelcomeMessage(client);
}

private void sendWelcomeMessage(Socket client) throws IOException {
 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
 writer.write("Hello. You are connected to Server. What is your name?");
 writer.flush();
}

/**
* Creates a SocketServer object and starts the server.
*
* @param args
*/
public static void main(String[] args) {
 // Setting a default port number.
 int portNumber = 1234;

 try {
 // initializing the Socket Server
 Server socketServer = new Server(portNumber);
 socketServer.start();

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

Клиент:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

private String hostname;
private int port;
Socket socketClient;

public Client(String hostname, int port){
 this.hostname = hostname;
 this.port = port;
}

public void connect() throws UnknownHostException, IOException{
 System.out.println("Attempting to connect to "+hostname+":"+port);
 socketClient = new Socket(hostname,port);
 System.out.println("Connection Established");
}

public void readResponse() throws IOException{
 String userInput;
 BufferedReader stdIn = new BufferedReader(new InputStreamReader(socketClient.getInputStream()));

 System.out.println("Response from server:");
 while ((userInput = stdIn.readLine()) != null) {
 System.out.println(userInput);
 }
}

public static void main(String arg[]){
 //Creating a SocketClient object
 Client client = new Client ("localhost",1234);
 try {
 //trying to establish connection to the server
 client.connect();
 //if successful, read response from server
 client.readResponse();

 } catch (UnknownHostException e) {
 System.err.println("Host unknown. Cannot establish connection");
 } catch (IOException e) {
 System.err.println("Cannot establish connection. Server may not be up."+e.getMessage());
 }
}
}
1 ответ

Я не буду давать вам ответы на все вопросы, но вот подсказка о том, как установить соединение со стороны сервера:

private Connection conn = null;
 public void connect(){
 try {
 Class.forName("com.mysql.jdbc.Driver").newInstance();
 conn = 
 DriverManager.getConnection("jdbc:mysql://mysql.agh.edu.pl/db_name",
 "username","password");

 ...

 } catch (SQLException ex) {
 // handle any errors
 System.out.println("SQLException: " + ex.getMessage());
 System.out.println("SQLState: " + ex.getSQLState());
 System.out.println("VendorError: " + ex.getErrorCode());
 }catch(Exception e){e.printStackTrace();} 
 }

И вот как подключиться с сайта клиента:

private Connection conn = null;
 private Statement stmt = null;
 private ResultSet rs = null;
 ..... .......
 connect();
 stmt = conn.createStatement();

 rs = stmt.executeQuery("SELECT name FROM users");

 while(rs.next()){
 String name = rs.getString(1);
 System.out.println("User: "+name);
 }

licensed under cc by-sa 3.0 with attribution.