为什么在sql语句中取代值而不是列名?

时间:2018-01-26 07:00:54

标签: sql sql-server jsp

我正在尝试从jsp文件向我的sql表添加一个新行。为此,我使用了prepareStatement,但在执行语句时,sql server将输入的值作为列名。

以下是我的相关代码:

<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>XYZ Web Application | Creating New User Account</title>
</head>
<body>

<%
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        Connection connection = 
DriverManager.getConnection("jdbc:sqlserver://127.0.0.1; 
databaseName=UserRecords; " +
                "username=name; password=password");

        Statement statement1 = connection.createStatement();
        if(statement1.executeQuery("select * from Users where username = " + 
username + " or email = " + email) != null){
            out.println("The username or email that you entered is already 
exist");
        }else{
            PreparedStatement statement = 
connection.prepareStatement("insert into UserRecords.Users (username, 
password, email) values(?,?,?)");
            statement.setString(1, username);
            statement.setString(2, password);
            statement.setString(3, email);

            statement.executeUpdate();
            out.println("Your account has been created. Go back to the home 
page to login.");
        }
    }catch (SQLException e){
        out.println("New user could not be created ..!");
        e.printStackTrace();
    }catch (ClassNotFoundException e){
        e.printStackTrace();
    }

%>
<a href="http://localhost:8080/UserInterfaces/Welcome.jsp" 
target="_blank">Home</a>

</body>
</html>

问题是sql server将输入的值作为列名,因此它返回invalid column name 'entered value',如上所述。例如,如果用户键入&#34; myusername&#34;,则返回invalid column name 'myusername'  我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

您需要使用单引号转义字符串文字。该错误是由您的数据库将这些字符串文字解释为列名称引起的,这不是您想要的。我将解决选择查询。以下是原始查询的外观:

select *
from Users
where username = 'username' or email = 'email';

可以在技术上在你的连接字符串中添加单引号。但是,正如您所见,这种方法容易出错,并且还会将您的应用程序打开到SQL注入攻击。对您而言,最好的方法可能是使用准备好的语句。以下是使用预准备语句处理上述选择查询的方法:

String sql = "select * from Users where username = ? or email = ?;";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, email);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
    String uname = rs.getString("username");
    String em = rs.getString("email");
}