- 论坛徽章:
- 0
|
1.要有数据库,表,直连!以mysql为例,sqlserver完全相同!
create database accp;
use accp;
create table userinfo(
id int auto_increment primary key,
userName varchar(20)
);
insert into userinfo(userName) values ('xiao');
insert into userinfo(userName) values ('bei');
insert into userinfo(userName) values ('meng');
2.在Eclipse中new 一个 web project
3.copy下属内容到jakarta-tomcat-5.5.9\conf\context.xml中sqlSever:
Resource name="jdbc/sqlServer"
type="javax.sql.DataSource"
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs" username="sa"
password=""/>
mysql:
Resource name="jdbc/sqlServer"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/accp" username="root"
password="mysql"/>
4.给tomcat/common/lib目录下,copy 数据库的驱动包
连接池建立完毕!
建立一个jsp文件,进行访问,也可以在类中访问,注意:必须在tomcat环境下,不支持main方法!
%@ page language="java" import="java.util.*,java.sql.*,javax.sql.*,javax.naming.*" pageEncoding="ISO-8859-1"%>
%
try
{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:/comp/env/jdbc/sqlServer");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from userinfo");
while(rs.next())
{
out.println(rs.getString(2)+"
");
}
}catch(Exception ex)
{
out.println(ex);
}
%>
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/66950/showart_1133593.html |
|