這次是怎樣將大象放冰箱的命題了!大家都懂的!
我們要解決的主要有兩個問題:
1、如何獲取輸入的內容
2、如何插入時間。
直接上代碼
[html]
<%@ 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>
作者:shirenfeigui