Java EE(Java Platform, Enterprise Edition)是一个用于开发企业级应用的Java平台。连接MySQL数据库是Java EE应用中常见的需求。以下是连接MySQL的基本步骤和相关概念:
pom.xml
中添加以下依赖:pom.xml
中添加以下依赖:context.xml
中配置:context.xml
中配置:JdbcTemplate
或DataSource
进行数据库操作。以下是一个简单的示例,展示如何在Servlet中使用DataSource连接MySQL数据库:
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@WebServlet("/db")
public class DBServlet extends HttpServlet {
private DataSource dataSource;
@Override
public void init() throws ServletException {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
} catch (Exception e) {
throw new ServletException("Cannot obtain DataSource", e);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable")) {
while (rs.next()) {
out.println(rs.getString("columnName"));
}
} catch (SQLException e) {
out.println("SQL Error: " + e.getMessage());
}
}
}
通过以上步骤和示例代码,你应该能够在Java EE应用中成功连接MySQL数据库。
领取专属 10元无门槛券
手把手带您无忧上云