简体   繁体   English

如何使用jdbc在mysql中插入撇号数据

[英]how to insert apostrophe data in mysql using jdbc

I am trying to insert few details for product which includes id, title, category , etc... 我正在尝试为产品插入一些详细信息,包括ID,标题,类别等。

Now in title field, my data is like: "Voi Jeans Banana Fit Men's Trousers", But on insertion I'm getting below error: 现在在标题字段中,我的数据就像:“ Voi Jeans Banana Fit男士长裤”,但是在插入时,我遇到了以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your     SQL syntax; check the manual that corresponds to your MySQL server version for the right   syntax to use near 's Trousers' ,'http://www.flipkart.com/voi-jeans-banana-fit-men-s- trousers/p/itmd' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2619)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1709)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1628)
at     universe.shopping.controller.shoppingcontrol.processrequest(shoppingcontrol.java:388)
at universe.shopping.controller.shoppingcontrol.doGet(shoppingcontrol.java:88)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Which as far as i know basically sql interpret this data as "Voi Jeans Banana Fit Men" instead of "Voi Jeans Banana Fit Men's Trousers" excluding "s Trousers" part causing an error. 据我所知,基本上sql会将此数据解释为“ Voi Jeans Banana Fit Men's Trousers”,而不是“ Voi Jeans Banana Fit Men's Trousers”(“ s Trousers”部分除外)导致错误。

I really need to know how can i insert the complete title with apostrophe included. 我真的需要知道如何插入带有撇号的完整标题。 What's the best possible way? 最好的方法是什么?

My jdbc code where I'm doing my insertion is: 我在其中插入的jdbc代码是:

String pid=request.getParameter("id");  // values from my jsp form 
String pname=request.getParameter("name");
String plink=request.getParameter("link");
String pkeyword1=request.getParameter("keyword1");
String pcategory=request.getParameter("catval");
String psubcategory=request.getParameter("cval");
String psubsubcategory=request.getParameter("subcval");
String pimage=request.getParameter("image");
String psecondimage=request.getParameter("secondimage");
String pthirdimage=request.getParameter("thirdimage");
String pcontent=request.getParameter("content");
String pprice=request.getParameter("price");
String pshipping=request.getParameter("shipping");
String pquantity=request.getParameter("quant");

java.sql.Connection connection = null;
CallableStatement stmt=null;
try {  
    Class.forName("com.mysql.jdbc.Driver");  
} catch (ClassNotFoundException e) {  
    System.out.println("Where is your MySQL JDBC   Driver?");  
    e.printStackTrace();  
    return;  
}  

System.out.println("MySQL JDBC Driver Registered!");  
Connection con = null;  
try {  
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/grandsho_register", "root","123456");  
} catch (SQLException e) {  
    System.out.println("Connection Failed! Check output console");  
    e.printStackTrace();  
    return;  
}  
if (con != null) {  
    System.out.println("Connection made.....");  
    try{  
        System.out.println("creating statements...");  
        String sql="{call adminproduct('"+pid+"','"+pname+"'   ,'"+plink+"' ,'"+pkeyword1+"','"+pprice+"','"+pshipping+"','"+pquantity+"','"+pcategory+"','"+psubcategory+"','"+psubsubcategory+"','"+pimage+"','"+psecondimage+"','"+pthirdimage+"','"+pcontent+"')}";
        stmt=con.prepareCall(sql);
        stmt.executeUpdate(sql);   
        System.out.println("Inserted records into the table...");  

        stmt.close();  
        con.close();  
    }catch(SQLException se){  
        se.printStackTrace();  
    }
}else {  
    System.out.println("Failed to make connection!");  
}  

Please suggest me an appropriate solution to insert this data from jdbc. 请建议我一个合适的解决方案,从jdbc插入此数据。

Rather than do this: 而不是这样做:

 String sql="{call adminproduct('"+pid+"','"+pname+"'   ,'"+plink+"' ,'"+pkeyword1+"','"+pprice+"','"+pshipping+"','"+pquantity+"','"+pcategory+"','"+psubcategory+"','"+psubsubcategory+"','"+pimage+"','"+psecondimage+"','"+pthirdimage+"','"+pcontent+"')}";

you should investigate PreparedStatements . 您应该调查PreparedStatements

essentially you provide a SQL statement which placeholders and declare what parameters go in each placeholder. 本质上,您提供了一个SQL语句,其中包含占位符,并声明每个占位符中包含哪些参数。 This makes use of the database APIs such that you don't have to escape apostrophes etc., and protects you against SQL injection . 这将利用数据库API,这样您就不必转义撇号等, 并且可以防止SQL注入

You should use parameterized SQL instead of including the values directly within the call itself. 您应该使用参数化的SQL,而不是直接在调用本身中包含值。 So something like: 所以像这样:

// The ... is because I didn't want to count the huge number of parameters...
// You'll need to fill in the right number of question marks.
String sql = "{call adminproduct(?, ?, ?, ?, ?, ...))}";
stmt = con.prepareCall(sql);
stmt.setString(1, pid);
stmt.setString(2, pname);
// Etc... all the parameters
stmt.executeUpdate(sql);   

Never include variable values directly within SQL, whether they're calling a stored proc or vanilla SQL. 不论变量值是调用存储的proc还是普通的SQL,都不要直接在SQL中包含变量值。 There are three primary benefits in using parameterized SQL: 使用参数化SQL有三个主要好处:

  • It protects against SQL injection attacks 它可以防止SQL注入攻击
  • It avoids messy conversions (particularly for date/time fields) 它避免了混乱的转换(尤其是对于日期/时间字段)
  • It keeps your code cleaner, by separating the SQL from the values. 通过将SQL与值分开,可以使代码更整洁。 (The SQL is much easier to read without all that string concatenation.) (该SQL是容易不所有字符串连接阅读。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM