// You can use this sample servlet as a starting point to connect
//簡單servlet連結oracle修改語法。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public
class Ex63 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
ServletOutputStream sos = res.getOutputStream();
PrintWriter out = new PrintWriter(sos,true);
out.println("<html>");
out.println("<head><title>Hello World</title></head>");
out.println("<body>");
try {
// The newInstance() call is a work around for some
// broken Java implementations
out.println("測試");
Class.forName("oracle.jdbc.OracleDriver").newInstance();
}
catch (Exception E) {
out.println("Unable to load driver.");
E.printStackTrace();
}
out.println("<br><hr>");
try {
Connection Conn =
DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","user","password");
// Do something with the Connection
Statement Stmt = Conn.createStatement();
ResultSet RS = Stmt.executeQuery("SELECT var1 from testtable");
String nameStr = req.getParameter("Name");
String sql2 = "insert into testtable(var1) values('"+nameStr+"')";
//DatabaseMetaData dm = Conn.getMetaData();
//ResultSet tb = dm.getTables(null,null,"testtable",null);
if(nameStr!=null&&nameStr!=""){
Stmt.executeUpdate(sql2);
out.println("有執行sql2<br>");
}
while (RS.next()) {
out.println(RS.getString(1));
}
out.println("<br><hr>");
out.println("你輸入的字串是"+nameStr+"<br>");
out.println("你輸入的sql語法是"+sql2+"<br>");
// Clean up after ourselves
RS.close();
Stmt.close();
Conn.close();
}
catch (SQLException E) {
out.println("SQLException: " + E.getMessage());
out.println("SQLState: " + E.getSQLState());
out.println("VendorError: " + E.getErrorCode());
}
out.println("</body></html>");
}
public String getServletInfo() {
return "Create a page that says <i>Hello World</i> and send it back";
}
}
沒有留言:
張貼留言