为什么INSERT查询在此HttpServer代码中不起作用

时间:2012-10-31 14:00:34

标签: java mysql jdbc insert

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

我的服务器类如下:

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

2 个答案:

答案 0 :(得分:4)

在你需要做executeUpdate陈述之后。

con.commit();

保存交易。

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

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

更改名称可解决问题。

<小时/> 现在与您的问题无关,您应该使用PreparedStatement而应该关闭您的连接和声明

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

答案 1 :(得分:2)

首先,使用 prepared statement[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 (?,?,?,?)";