我目前在从mySQL数据库中选择某个项目时遇到问题。我的程序旨在将一个参数从android应用程序传递给servlet,然后servlet查询数据库。
但是控制台窗口上出现错误: 'where子句'中的未知列'0102310c24'
当我想要选择的值包含字母时,只有一个错误。
当我查询这个号码0106172459时,我想要的数据没有问题。
下面是我的servlet。
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBServlet extends HttpServlet {
public void service(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String x=request.getParameter("item");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection ("jdbc:mysql://IP/databasename", "username", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM items WHERE item="+x);
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print(",");
out.print(rs.getObject(2).toString());
out.print(",");
out.print(rs.getObject(3).toString());
out.print(",");
out.print(rs.getObject(4).toString());
out.print(",");
out.print(rs.getObject(5).toString());
out.print(",");
out.print(rs.getObject(6).toString());
out.print(",");
out.print(rs.getObject(7).toString());
out.print(",");
out.print(rs.getObject(8).toString());
out.print(",");
out.print("\n");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
我使用它将值发送到servlet。
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("item","List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("item","010238a2cc"));"));
如果有人能提供帮助,我将感激不尽
答案 0 :(得分:13)
值x
应该用引号括起来,否则将假定非数字值引用列而不是字符串文字。
rs = stmt.executeQuery("SELECT * FROM items WHERE item='"+x + "'");
请注意,您的脚本似乎容易受到SQL注入攻击,因为值x
尚未转义,但已从Request
收到。最好在这里使用准备好的声明。
答案 1 :(得分:2)
尝试使用PreparedStatement
。
PreparedStatement st = con.prepareStatement("SELECT * FROM items WHERE item=?");
st.setString(1,x);
rs = st.executeQuery();
答案 2 :(得分:0)
如果项目是String类型,则需要将其括在引号中。更好的是,您应该使用PreparedStatement来执行查询。
答案 3 :(得分:0)
如果值x是整数,则使用以下代码: - rs = stmt.executeQuery(“SELECT * FROM items WHERE item =”+ x); 如果值x是字符串,则使用以下代码: - rs = stmt.executeQuery(“SELECT * FROM items WHERE item ='”+ x“'”);