字符串java后的unclosed引号

时间:2014-10-25 09:24:09

标签: java

我正在阅读3个pakets,如邮件到邮件主题和邮件消息,但当我将数据插入数据库时​​,我得到此错误,这是代码的一部分

aSocket.receive(to);
String towards=new String(to.getData());
System.out.println(towards);
aSocket.receive(sub);
String subject=new String(sub.getData());
aSocket.receive(msg);
String message=new String(msg.getData());
sendedmail(towards,subject,message,username);

public void sendedmail(String to,String sub,String msg,String from){
    try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    }catch(ClassNotFoundException ex){
        JOptionPane.showMessageDialog(null,ex.getMessage());
    }
    try{
        Connection con=DriverManager.getConnection("jdbc:odbc:udp");
        Statement st=con.createStatement();
        int status=0;
        String query;
        query = "INSERT INTO emails(emailto, emailfrom, message, userstatus, subject) VALUES('"+to+"','"+from+"','"+msg+"','"+status+"','"+sub+"')";
        int f=st.executeUpdate(query); 
        if(f==1){
            System.out.println("row inserted");
        }
        else
        {
            System.out.println("row not inserted");
        }  
    }catch(SQLException ex){
        JOptionPane.showMessageDialog(null,ex.getMessage());
    }

1 个答案:

答案 0 :(得分:2)

在SQL中,引号通过加倍来转义,例如:

insert ... values ('O''Brien');

所以你需要用双引号替换所有引号:

 str = str.replace("'", "''");

哦,自从你需要在使用它之前加载JDBC驱动程序类以来已经有15年了。只需删除整个第一个try-catch。