用eclipse建了个j2ee web工程,里头就一个类和一张jsp页面,读数据库:
----------------------------------------
DBConn.java:
package com.test.DB;
import java.sql.*;
import java.io.*;
import java.util.*;
public class DBConn
{
private Connection conn=null;
public Connection getConnection() throws SQLException
{
String Driver= "net.sourceforge.jtds.jdbc.Driver ";
String URL= "jdbc:jtds:sqlserver://222.31.170.89:1433/bookshop ";
String UserName= "sa ";
String PassWord= " ";
Connection conn=null;
try
{
Class.forName(Driver);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
try
{
conn=DriverManager.getConnection(URL,UserName,PassWord);
}
catch(SQLException e)
{
throw e;
}
return conn;
}
public PreparedStatement getPreparedStatement(String sql)
{
PreparedStatement ps=null;
try
{
conn=getConnection();
ps=conn.prepareStatement(sql);
return ps;
}
catch(Exception ee)
{
Close(ps);
ee.printStackTrace();
return null;
}
}
public void release()
{
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static int Close(PreparedStatement ps)
{
if(ps==null)
return 0;
try
{
ps.close();
return 0;
}
catch(SQLException e)
{
return -1;
}
}
}
----------------------------------------------
testDBConn.jsp:
<%@ page language= "java " import= "java.util.* " pageEncoding= "ISO-8859-1 "%>
<%@ page import= "com.test.DB.* " %>
<%@ page import= "java.sql.* " %>
<%@ page import= "java.io.* " %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+ ":// "+request.getServerName()+ ": "+request.getServerPort()+path+ "/ ";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN ">
<html>
<head>
<base href= " <%=basePath%> ">
<title> My JSP 'testDBConn.jsp ' starting page </title>
<meta http-equiv= "pragma " content= "no-cache ">
<meta http-equiv= "cache-control " content= "no-cache ">
<meta http-equiv= "expires " content= "0 ">
<meta http-equiv= "keywords " content= "keyword1,keyword2,keyword3 ">
<meta http-equiv= "description " content= "This is my page ">
<!--