Я пытаюсь написать свое первое клиент-серверное приложение, и у меня возникла проблема с выполнением sql-запроса на стороне сервера. Соединение установлено, но запрос не выполняется (если запрос проверяется отдельно от клиента и сервера, он работает).
Server.java:
import java.io.*;
import java.net.*;
import java.sql.*;
public class Server {
public static final int PORT = 8080;
public static void main(String[] args) throws IOException, SQLException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Started: " + s);
Socket socket = s.accept();
System.out.println("Connection accepted: " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
while (true) {
String command = in.readLine();
if (command.equals("add")){
DBqueries.addNewWord();
}
else if (command.equals("end")) break;
}
socket.close();
s.close();
}
}
Client.java:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
InetAddress addr = InetAddress.getByName(null);
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, Server.PORT);
System.out.println("socket = " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
System.out.println("Enter the command");
String command = in.readLine();
out.println(command);
socket.close();
}
}
А вот часть класса DBqueries.java с методом addNewWord ():
import java.sql.*;
import java.util.*;
public class DBqueries {
private static final String url = "jdbc:mysql://localhost:3306/vocabulary";
private static final String user = "root";
private static final String password = "password";
private static ResultSet rs;
private static Statement stmt;
public static void main(String args[])throws SQLException {
//String descriptionByWord = getDescriptionByWord();
addNewWord();
//deleteWord();
//updateWord();
//getWordByMask();
}
public static void addNewWord()throws SQLException {
Connection con = DBconnector.getConnection(url, user, password);
Scanner sc = new Scanner(System.in);
String whereClause;
System.out.print("Please enter the word for inserting:");
whereClause = sc.nextLine();
String query = "insert into voc_table (word)"+"values(?)";
try {
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, whereClause);
preparedStatement.executeUpdate();
preparedStatement.close();
con.close();
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}