sql查询不会在java应用程序的服务器端执行

fhity93d  于 2021-06-24  发布在  Mysql
关注(0)|答案(0)|浏览(225)

我正在尝试编写第一个客户机-服务器应用程序,但在服务器端执行sql查询时遇到问题。连接已经建立,但查询没有执行(如果查询是从客户机和服务器分别测试的,那么它就可以工作)。
服务器.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();
  }
}

客户端.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();
  }
}

下面是使用addnewword()方法的dbqueries.java类的一部分:

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();
    }
  }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题