ITPub博客

首页 > Linux操作系统 > Linux操作系统 > [转载]如何在Servlet中连接数据库

[转载]如何在Servlet中连接数据库

原创 Linux操作系统 作者:dinner1007 时间:2019-04-10 20:42:03 0 删除 编辑
如何在Servlet中连接数据库
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Database extends HttpServlet
{

public void doGet (
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException
{
PrintWriter out;
String title = "Simple Servlet connecting to Oracle DB";

// set content type and other response header fields first
response.setContentType("text/html;charset=GB2312");

// then write the data of the response
out = response.getWriter();

out.println(""); <br /> out.println(title); <br /> out.println("");
out.println("

" + title + "

");
out.println("

This is output from SimpleServlet.");
String driverName = "oracle.jdbc.driver.OracleDriver";
Driver d;
Connection con;
Statement stmt;
ResultSet results;


try {
d = (Driver)Class.forName(driverName).newInstance();
con = DriverManager.getConnection("jdbc:oracle:thin:ndb/ndb@111.222.1.36:1521:PC36");
stmt = con.createStatement();
String sqlstr = "select SYSDATE from dual";
results = stmt.executeQuery(sqlstr);
displayResult(results,out);
stmt.close();
con.close();
}
catch (Exception e) {
out.println("error: " + e.toString());
}
out.println("");
out.close();
}

public void displayResult(ResultSet results,PrintWriter out){
StringBuffer buf = new StringBuffer();
String temp;
try {
ResultSetMetaData rsmd = results.getMetaData();
int numCols = rsmd.getColumnCount();
int i, rowcount = 0;
// get column header info
for (i=1; i <= numCols; i++){
if (i > 1) buf.append(",");
buf.append(rsmd.getColumnLabel(i));
}
buf.append("
");
while (results.next() && rowcount < 100){
for (i=1; i <= numCols; i++) {
if (i > 1) buf.append(",");
buf.append((results.getString(i)));
}
buf.append("
");
rowcount++;
}
out.println("
");
out.println(buf.toString());
results.close();

} catch (Exception e) {
out.println("error: " + e.toString());

return;
}
}
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/374079/viewspace-132124/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2018-08-23

  • 博文量
    711
  • 访问量
    498879