簡體   English   中英

html單選按鈕添加到數據庫

[英]html radio button add to database

我有一個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();
%>

如果這兩個(窗體和jsp代碼)都在同一個文件(Question2.jsp)中,則在您第一次調用它時,它將為您提供NULL值。 將表單和代碼分別放在兩個不同的文件中,例如form.htmlQuestion2.jsp ,這可能會阻止您獲取NULL值。

檢查answer變量是否正確獲取值。

您已准備好語句,但尚未執行。

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

我假設您在“ Question2.jsp ”中有完整的代碼,並且在第一次執行JSP時。 它獲取NULL值。

此外,由於Connection僅返回PreparedStatement的對象,因此無需強制轉換(PreparedStatement)

<form>標記中添加method="post"

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

更新到數據庫后,關閉連接對象。

conn.close();

我想到了,

只是做類似的事情

將1個html頁面放在一個頁面中,而Question2.jsp放在另一頁面中

之后在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))之后,您的輸入將很好地插入

k。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM