您的位置:首页 > 数据库 > MySQL

jdbc数据源配置

2016-04-22 16:07 567 查看
1.      将mysql驱动(最好和mysql版本配套的驱动)放置在Apache Tomcat 下的lib目录里面

2.      在java web项目的WEB-INF下的web.xml中添加

<resource-ref>
<description>mysql</description>
<res-ref-name>jdbc/mysql</res-ref-name>    //(1)
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

3.在项目的META-INF目录的context.xml里面添加

<Resourcename="jdbc/mysql"              //(2)      (1)与(2)的名字要一致
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/showtime"      //数据库名在这修改
username="root"
password="123456"
maxActive="50"
maxIdle="20"
maxWait="10000" />
<span style="font-size:18px;"><span style="color: rgb(255, 0, 0); text-align: center; font-family: Arial, Helvetica, sans-serif;">----------------------- 配置后重启服务器</span><span style="color: rgb(255, 0, 0); text-align: center; font-family: Arial, Helvetica, sans-serif;"> --------------------------       </span></span>

<pre name="code" class="html"><strong>4. 上面已经配置完成,接下来 在jsp中添加测试程序 </strong>

<body>
<%
Context initCtx = new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:/comp/env/jdbc/mysql");//和前面配置一致
Connection conn = ds.getConnection();
Statement stmt =conn.createStatement();
String sql = "select * from user";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {
out.print("<br />" +"====================" + "<br />");
out.print(rs.getLong("id") +"   ");
out.print(rs.getString("username") + "   ");
}
%>
</body>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据源 jdbc mysql