JSP和Java中都可以使用JDBC技術來連接數據庫,但二者還是有些區別的。
在JSP中連接數據庫,需要在JSP頁面中使用Java代碼編寫連接數據庫的相關操作,這種方式在開發小型項目時是可行的,但對于大型項目卻不太適合。
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from stu_info");
while (rs.next()) {
out.println(rs.getString(1));
}
rs.close();
stmt.close();
conn.close();
而在Java中連接數據庫,通常使用DAO層來封裝數據訪問操作,使代碼更加簡潔易懂,而且更容易維護。
public class UserDao {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "123456";
private Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public List<User> getUserList() {
List<User> userList = new ArrayList<User>();
Connection conn = getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return userList;
}
}
從上面的代碼示例可以看出,在Java中連接數據庫更加規范,代碼更加清晰易懂。因此,在開發大型項目時,應該將數據庫訪問操作封裝到DAO層,以便項目開發和維護。
上一篇php 會話安全
下一篇css文字跟隨頁面縮小