所以我本周末刚学完JDBC并成功将我的代码从main方法转移到MVC应用程序中。此应用程序的目的是持有一个玩家名单,并在需要时显示用户凭据。该程序运行良好,当我请求像...的网址时
http://localhost:8084/gmustudent/players?id=1
我得到了该播放器的正确输出!问题是我在PlayersDAO类中执行数据库连接,我认为这不是“最好”的方法。所以我有两个问题。
任何评论或链接将不胜感激。我将分享我目前为DAO课程编写的代码,以便您可以看到我到目前为止所拥有的代码。谢谢大家!
package com.jdbc.test;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class PlayersDAO
{
public static Players viewPlayer(int id) throws SQLException
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Players playerObject = null;
try
{
String url = "jdbc:mysql://localhost:3306/gmustudent";
String username = "root";
String password = "root";
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM players WHERE id = " + id);
if(resultSet.next())
playerObject = new Players(resultSet.getLong("id"), resultSet.getString("name"), resultSet.getString("position"), resultSet.getString("height"), resultSet.getString("year"), resultSet.getString("hometown"), resultSet.getString("highschool"), resultSet.getString("headshot"));
}
finally
{
if (connection != null) try{connection.close();} catch(SQLException ignore) {}
if (statement != null) try{statement.close();} catch(SQLException ignore) {}
if (resultSet != null) try{resultSet.close();} catch(SQLException ignore) {}
}
return playerObject;
}
}
答案 0 :(得分:0)
您可以使用资源在web.xml文件中创建数据库连接。我希望本教程能为您提供帮助。
http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/
答案 1 :(得分:0)
您可以使用JDBC Connection Pooling。它可以在应用程序性能,并发性和可伸缩性方面提供显着优势。
答案 2 :(得分:0)