gpt4 book ai didi

java - sql server 数据插入错误

转载 作者:行者123 更新时间:2023-12-01 16:09:46 26 4
gpt4 key购买 nike

我尝试这段代码,这是在mssqlserver中传递值的问题我将一个页面的值传递到另一页,听到nrno的值来到其他页面,但听到错误是java.sql.SQLException:无效的列名'nrno'。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<body>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<%
String AppURL = request.getContextPath() ;
String thisFile = AppURL+request.getServletPath() ;
int nrno = 0;
try
{
nrno = Integer.parseInt(request.getParameter("rno"));
}
catch(NumberFormatException ex)
{
nrno = 0;
}
%>
<td>this is in roolno :- <%=nrno%> </td><br>
<%
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/sample", "sa", "sa1234");
java.sql.Statement stmt = conn.createStatement();
try
{
int val = stmt.executeUpdate("INSERT student (name,rno) VALUES('nikki',+ nrno)");
out.println("1 row affected");
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed!");
}
stmt.close();
conn.close();
%>
</body>
</html>

最佳答案

您不需要以下内容吗?

   int val = stmt.executeUpdate("INSERT student (name,rno) VALUES('nikki'," + nrno + ")");

在上面的示例代码中,您没有插入 nrno,而是插入实际的字符串 nrno 本身(因为它位于双引号)。

展望 future ,我会调查 PreparedStatements这样您就可以执行以下操作:

   PreparedStatement pstmt = con.prepareStatement("INSERT student (name,rno) VALUES(?,?)");
pstmt.setString(1, 'nikki');
pstmt.setInt(2, nrno);

并避免像上面这样令人讨厌的引用问题,加上可能的 SQL 注入(inject)问题(我意识到上面可能是一个练习或类似的问题,但这是一件需要注意的好事情)。

关于java - sql server 数据插入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1700464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com