mysql-connector-java-8.0.18.zip
sur le site officiel (https://dev.mysql.com/downloads/connector/j/) mysql-connector-java-5.1.48-bin.jar
/ WebContent / WEB-INF / lib / mysql-connector-java-5.1.48-bin.jar
Créer dans / WebContent / META-INF / context.xml
context.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
<Resource name = "jdbc/book"
auth = "Container"
type = "javax.sql.DataSource"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/book"
username = "namari"
password = "password">
</Resource>
</Context>
Créer dans / Sample / webapps / book / WEB-INF / src / chapitre14 / All.java
All.java
package chapter14;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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.*;
/**
* Servlet implementation class All
*/
@WebServlet("/All")
public class All extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public All() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
//Obtenir une connexion
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:/comp/env/jdbc/book");
Connection con = ds.getConnection();
//Transmission d'instruction SQL
PreparedStatement st = con.prepareStatement("select * from product");
//Exécution et réception des résultats
ResultSet rs = st.executeQuery();
//Affichage des données
while (rs.next()) {
out.println(rs.getInt("id") + ":" + rs.getString("name") + ":" + rs.getInt("price"));
}
//Déconnexion de la base de données
st.close();
con.close();
} catch (Exception e) {
//Erreur de connexion / instruction SQL
e.printStackTrace(out);
} // try
}
}
Recommended Posts