2016-07-10 25 views
0

表我使用下面的代碼使用JSP來插入表:插入到使用JSP

<%@ page import="java.sql.*" %> 
<%@ page language="java" import="java.sql.*" %> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<html> 
<head>conn</head> 
<body> 
<form action = "" method = "POST"> 
id : <input type = "text" name = "eid"> 
name: <input type="text" name="first_name"> 
<input type="submit" value="Submit" /> 
</form> 
<% 
String data1 = request.getParameter("eid"); 
String data = request.getParameter("first_name"); 
%> 

<% 
Connection conn = null; 
Statement stmt = null; 
ResultSet result = null; 
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","Password"); 
PreparedStatement ps = null; 
String query = "insert into employee(eid,ename) values(?,?)";  
ps = conn.prepareStatement(query); 
ps.setString(1,data1); 
ps.setString(2,data); 
ps.executeUpdate(); 
%> 
</body> 
</html> 

我收到錯誤「ORA-01400:無法將NULL插入(」「」 SYSTEM EMPLOYEE 「。」EID「)」

即使在表單出現之前,我收到了此錯誤。 爲什麼插入發生在我點擊提交按鈕之前。

謝謝!

回答

1

如果你想要讓你的JSP能夠張貼到自身和工藝要求我可能會做到以下幾點:

<% 

String eid = request.getParameter("eid"); 
String first_name = request.getParameter("first_name"); 
if(eid != null && first_name != null){ 
    Connection conn = null; 
    Statement stmt = null; 
    ResultSet result = null; 
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); 
    try{ 
     conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","Password"); 
     PreparedStatement ps = null; 
     String query = "insert into employee(eid,ename) values(?,?)";  
     ps = conn.prepareStatement(query); 
     ps.setString(1,eid); 
     ps.setString(2,first_name); 
     ps.executeUpdate(); 
    }catch(SQLException sqle){ 
     //log sql exception  
    } finally { 
     if(conn != null){ 
      try{ 
       conn.close(); 
      }catch(SQLException sqle){ 
       //log exception 
      } 
    } 
} 
%> 

請記住,JSP所有的工作都做完了服務器端,所以如果有一個在您的代碼大多會發生在你的頁面將得到完全呈現一個邏輯錯誤。如果你想查詢數據庫,那麼你應該確保你發送了必要的信息。您可以通過訪問JSP頁面的請求對象來獲取該信息。接下來,我在你的代碼中加入一條if語句來確保這兩個值被填充。最後我將代碼放在try/catch/finally結構中,以確保數據庫連接已關閉。最後一點對你來說可能並不是什麼大事(我認爲你是爲一些課程做這個或者只是爲了學習),但是如果你長時間運行一臺服務器並且忘記關閉它會遇到問題數據庫連接。

1

頁面加載時,在服務器端執行<%>內的每個塊,並將結果傳遞給頁面。因此,你會得到上述行爲。

您的區塊<%>與fom無關。

2

如果你想用JSP只是工作:

你可以把所有<% %>之間的代碼在你的數據傳遞到它

另一個JSP頁,但它不是一個很好的做法,建議工作與servletjsp獲得數據並將它傳遞給豆,也在bean你把你的代碼與數據庫連接...