怎样用servlet进行对数据库的操作
1个回答
展开全部
1、首先明确一点,servlet就是一个继承自javax.servlet.http.HttpServlet的类。
2、范例:使用servlet连接数据库
package com.oracle.project.servlet ;
import java.util.* ;
import java.io.* ;
import java.sql.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;
import javax.servlet.annotation.* ;
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ;
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:ORACLEDB" ;
public static final String DBUSER = "scott" ;
public static final String PASSWORLD = "tiger" ;
private Connection conn = null ;
public Connection getConnection() {
try {
if(this.conn == null) {
Class.forName(DBDRIVER) ;
this.conn = DriverManager.getConnection(DBURL,DBUSER,PASSWORLD) ;
}
} catch(Exception e) {
e.printStackTrace() ;
}
return conn ;
}
@Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
PrintWriter out = response.getWriter() ;
out.println("<html>") ;
out.println("<body>") ;
out.println("<h1>" + this.getConnection() + "</h1>") ;
out.println("</body>") ;
out.println("</html>") ;
}
@Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
this.doGet(request,response) ;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询