2011年10月5日 星期三

Statement

----------------------輸入t1.jsp----------------------------


<%@page contentType="text/html;charset=Big5" import="java.util.*"%>
<HTML>
<HEAD>
<TITLE>帳密留言</TITLE>
</HEAD>
<BODY>
<form method="post" action="insert.jsp">
帳號 <Input name="na" type="text">

</br>

<Input type=submit name=sb value="送出">


<Input type=reset name=rt value="清除">
</form>
</BODY>
</HTML>


------------------database_setup.jsp-------------------

<%@ page import="java.sql.*" %>
<%
Connection conn = null;
Statement stmt = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//載入連資料庫的驅動程式
conn=DriverManager.getConnection("jdbc:odbc:test");//抓資料來源
stmt=conn.createStatement();//建立敘述
}catch(SQLException sqle){
out.println("SQL Exception"+sqle);
}


%>


----------------------query.jsp----------------------------


<%@ include file="database_setup.jsp" %>
<html>
<head><title>query</title></head>
<body>
<%

String sql="select * from Table1";//取出Table1的所有欄位
ResultSet rs=stmt.executeQuery(sql);//執行SQL語法

out.println("<table border='1'>");
out.println("<tr>");
out.println("<td> Name</td>");
out.println("<td>Num</td>");
out.println("</tr>");
while(rs.next()){
String name=rs.getString("col1");
String num=rs.getString("id");
out.println("<tr>");
out.println("<td>"+name+"</td>");
out.println("<td>"+num + "</td>");
out.println("</tr>");
}
out.println("</table>");
rs.close();
%>

</body>
</html>


---------------------insert.jsp---------------------------

<%@ include file="database_setup.jsp" %>

<%
 if(request.getParameter("insert")!=null){
String name=request.getParameter("col1");
String sql="insert into table1(col1) values('"+name+"')";
int a = stmt.executeUpdate(sql);
 }

%>
<html>
<head><title>insert</title></head>
<body>
<form action="insert.jsp" method="post">
 Name:<input type="text" name="col1" size="10">
 <br/>
 <input type="submit" name="insert" value="Insert">
</form>
<a href="query.jsp">check</a>

</body>
</html>

沒有留言:

張貼留言