日期:2014-05-16  浏览次数:20525 次

JSP中的数据库操作(3):JSP页面中的数据库插入

这次是怎样将大象放冰箱的命题了!大家都懂的!

我们要解决的主要有两个问题:

1、如何获取输入的内容

2、如何插入时间。

直接上代码

<%@ page language="java" import="java.util.*, java.sql.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%request.setCharacterEncoding("UTF-8");%> 
<%response.setCharacterEncoding("UTF-8");%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<style type="text/css">
table{ width:800px; margin:auto; padding: 5px; font-size:12px; border:0px; background:#00CCFF;}
tr{ background:#fff;}
td{ padding: 5px;}
#title{ text-align:center;}
</style>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档11</title>
</head>

<body>
 <form method=post>
 	标题:<input type="text" name="title"/><br/>
 	内容:<input type="text" name="content"/><br/>
 	<input type="submit" value="提交" />
 </form>
 <%
 //连接MySQL数据库 
 	Class.forName("com.mysql.jdbc.Driver").newInstance();
  	String url="jdbc:mysql://localhost:3306/news";
  	String user="root";
  	String password="1234";
  	Connection conn = DriverManager.getConnection(url, user, password);
  	Statement st = conn.createStatement();
  	
 %>
  	<table >
  <tr>
    <td width="174" id="title">标题</td>
    <td width="449" id="title">内容</td>
    <td width="161" id="title">时间</td>
  </tr>
  	
<%
  	
  	ResultSet rs = st.executeQuery("SELECT * FROM data ORDER BY id DESC LIMIT 10");
  	while(rs.next()){%>
	
  <tr>
    <td width="174" ><%=rs.getString("title") %></td>
    <td width="449" ><%=rs.getString("content") %></td>
    <td width="161"><%=rs.getString("time") %></td>
  </tr>

<%} %>
 </table>

<%
//通过input中的name获取输入的内容。time那一行是获得时间及定义时间格式
	String getTitle=request.getParameter("title"); 
	String getContent=request.getParameter("content");
	java.text.SimpleDateFormat time = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
	String insertSQL = "INSERT INTO data(title, content, time) Values ('"+getTitle+"', '"+getContent+"', ' "+time.format(new java.util.Date())+"')";
	st.executeUpdate(insertSQL);
 %>
<%
	rs.close();
	st.close();
  	conn.close();
 %> 
</body>
</html>

本代码有个问题就是每次刷新网页都会insert一条!打开页面倒是不会。这怎么解决呢?