2

我试图为我的家庭作业制作一个小服务器。这是一个非常简单的项目,但我无法将一些变量(我从客户端以对象形式通过序列化获取)插入到数据库中。它显示没有错误!这就是我觉得奇怪的地方,客户也收到了没有问题的响应。

我的服务器类如下:

package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.ietf.jgss.Oid;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Server {

public static void main(String[] args) throws Exception {

    HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);

    server.createContext("/", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
}

static class MyHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
        ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
        final String url = "jdbc:mysql://localhost/httpServer";

        final String user = "root";

        final String password = "";

        try {
            Send oin = (Send) ios.readObject();

            String response = "Kjo eshte nje pergjigje nga serveri! \n"
                    + "Clienti me id "
                    + oin.getId()
                    + " dhe me emer "
                    + oin.getName()
                    + " ka pasur "
                    + oin.getAmount()
                    + "$ ne llogarine e tij ,por me pas ka terhequr "
                    + oin.getPaid()
                    + "$ nga llogaria \n"
                    + "Kjo terheqe eshte ruajtur ne database dhe tani gjendja e re eshte "
                    + (oin.getAmount() - oin.getPaid()) + "$ \n";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
            int id = oin.getId();
            String emri = oin.getName();
            int amount = oin.getAmount();
            int paid = oin.getPaid();
            try {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con = DriverManager.getConnection(url, user,
                        password);

                try {
                    Statement s = con.createStatement();

                    s.executeUpdate("INSERT INTO person VALUES ('" + id
                            + "','" + emri + "','" + amount + "','" + paid
                            + "')");
                } catch (SQLException s) {

                    System.out
                            .println("Tabel or column or data type is not found!");
                }

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

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

    }
}
   }

你能帮我么 ?或者知道问题可能是什么?

编辑:也许我在客户端做错了什么:

package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;

class Send implements Serializable {
// duhet te implementoje interfacin serizable ne menyre qe tja dergoj
// serverit
private static final long serialVersionUID = 1L;

public int getId() {
    return id;
}

public int getAmount() {
    return amount;
}

public int getPaid() {
    return paid;
}

int id = 1;
int amount = 2000;
int paid = 800;
String name = "Andi Domi";

public String getName() {
    return name;
}
    }

   public class Client {
public static void main(String[] args) throws Exception {

    try {

        URL url = new URL("http://localhost:3333");
        HttpURLConnection s = (HttpURLConnection) url.openConnection();
        s.setDoOutput(true);
        s.setDoInput(true);
        s.setRequestMethod("POST");
        s.setUseCaches(false);
        Send obj = new Send();
        ObjectOutputStream objOut = new ObjectOutputStream(
                s.getOutputStream());
        objOut.writeObject(obj);

        InputStream in = s.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(isr);
        int c;
        while ((c = br.read()) != -1) {
            System.out.print((char) c);
        }
        objOut.close();
        s.disconnect();
    } catch (IOException ex) {
        System.err.println(ex);
        System.err.print("gabimi eshte ketu");
    }
    }
    }
4

2 回答 2

4

在你的executeUpdate声明之后你需要做的。

con.commit();

保存交易。

编辑:根据聊天讨论,我们了解到命名的列emri实际上Emri在表中并且正在抛出:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'emri' in 'field list' 

更改名称可以解决问题。


现在与您的问题无关,您应该使用 aPreparedStatement并且应该关闭您的连接和语句

try {
  PreparedStatement s = con.prepareStatement("INSERT INTO person(id, emri, amount, paid) VALUES (?,?,?,?)");
  s.setInt(1,id);
  s.setString(2,emri);
  s.setInt(3,amount);
  s.setInt(4,paid);
  int count =  s.executeUpdate();
  con.commit();
} catch(Exception e){
  e.printStackTrace();
  //something bad happened rollback 
  //any uncommitted changes
  con.rollback();
} finally {
  if (con != null) {
    con.close();
  }
}
于 2012-10-31T14:03:56.080 回答
2

首先,使用准备好的语句[docs]来避免SQL INJECTION

String sql = "INSERT INTO person VALUES (?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1,id);
prest.setString(2,emri);    // or use setInt for integer
prest.setString(3,amount);  // or use setInt for integer
prest.setString(4,paid);
prest.executeUpdate() 

其次,如果值的数量与表中的总列数不匹配,它也会失败,因为您使用的是隐式类型的 INSERT 语句。要解决它,只需提供要存储值的列名,例如

String sql = "INSERT INTO person (col1, col2, col3, col4) VALUES (?,?,?,?)";
于 2012-10-31T14:11:22.907 回答