2012-03-29 92 views
0

我有一個html單選按鈕。當用戶點擊提交按鈕時,我想要將該值添加到數據庫表中。html單選按鈕添加到數據庫

有4個單選按鈕

o a 
o b 
o c 
o d 

---我已經使用的request.getParameter()和我所引述Q1。但是當我檢查數據庫表中是否添加了「null」時。 如何在數據庫中添加值?

這裏是我的html單選按鈕。

<FORM ACTION="Question2.jsp"> 
Q1. This is the section of code that gracefully responds to exceptions.<P> 
    <INPUT TYPE=RADIO NAME="q1" VALUE="a"/>a. Exception generator<BR> 
    <INPUT TYPE=RADIO NAME="q1" VALUE="b"/>b. Exception manipulator<BR> 
    <INPUT TYPE=RADIO NAME="q1" VALUE="c"/>c. Exception handler<BR> 
    <INPUT TYPE=RADIO NAME="q1" VALUE="d"/>d. Exception monitor<P> 
    <INPUT TYPE=SUBMIT VALUE="submit"/> 
</FORM> 

...這裏我試圖在表中添加值。

<% 
String query = "INSERT INTO Quiz2 VALUES (?)"; 
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(query); 
String answer = request.getParameter("q1"); 
pst.setString(1, answer); 
pst.executeUpdate(); 
%> 

回答

0

<form>標籤添加method="post"

<FORM ACTION="Question2.jsp" method="post"> 

並在更新到數據庫後關閉連接對象。

conn.close(); 
0

檢查answer變量是否正確得到了該值。

+0

System.out.print(answer);但因爲它是一個jsp沒有顯示出來。 – 2012-03-29 01:26:03

+0

是System.out.print'(答案);'會寫在服務器控制檯的值。你可以用'out.print(answer);'在jsp scriptlet中打印。或'$ {param.q1}'或'$ {PARAM [Q1]}'(外側的scriptlet),或'<%=請求。getParameter(「q1」)%> – tusar 2012-03-29 05:50:50

0

你準備好了你的陳述,但你還沒有執行它。

+0

只是沒有添加它的這段代碼。 – 2012-03-29 01:59:35

0

您是否嘗試過多次執行此操作?

我假設你有完整的代碼在「Question2.jsp」和第一次JSP得到執行。它獲得NULL的值。

更多的,沒有必要輸入(PreparedStatement)作爲Connection只返回PreparedStatement的對象。

1

如果雙方的這個(形式和JSP代碼)都在同一個文件(Question2.jsp),那麼,當你把它第一次它會給你NULL值。獨立的形式,並在兩個不同的文件爲form.htmlQuestion2.jsp的代碼,這可能會阻止您獲得NULL值。

0

我想通了,

只是做的事情就像

發生在後一頁和Question2.jsp在另一頁

你1個html頁面中question2.jsp地方的代碼這樣

<%@page import="java.sql.*" %> 


<% 
Connection conn=null; 
Statement stmt=null; 
ResultSet rs=null; 

String a=request.getParameter("q1"); 
System.out.println("Q1-->"+a); 
Class.forName("com.mysql.jdbc.Driver"); 
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/your database","your database username ","password"); 
System.out.println("connected"); 

stmt=conn.createStatement(); 
stmt.execute("insert into first(username) values('"+a+"')"); 

%> 

在此之後在數據庫中的地點ID(INT)名稱(VARCHAR(150))您的輸入將很好地插入

ķ。