Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.sql.DriverManager; // gestion des pilotes
- import java.sql.Connection; // une connexion `a la BD
- import java.sql.Statement; // une instruction
- import java.sql.ResultSet; // un r´esultat (lignes/colonnes)
- import java.sql.SQLException; // une erreur
- public class JdbcSample {
- // chargement du pilote
- private String driverName = "com.mysql.jdbc.Driver";
- public void loadDriver() throws ClassNotFoundException
- {
- Class.forName(driverName);
- }
- // ouverture de connexion
- private String url = "jdbc:mysql://localhost/mon_blog";
- private String user = "ts2";
- private String password = "ts2";
- public Connection newConnection() throws SQLException {
- Connection connect = DriverManager.getConnection(url, user, password);
- return connect;
- }
- // execution d’une requete
- final String monblog = "SELECT BIL_ID, BIL_DATE, BIL_TITRE, BIL_CONTENU FROM t_billet;";
- public void listMonBlog() throws SQLException {
- Connection connect = null;
- try {
- // create new connection and statement
- connect = newConnection();
- Statement st = connect.createStatement();
- ResultSet rs = st.executeQuery(monblog);
- while (rs.next()) {
- /*System.out.printf("%-20s | %-20s | %3d\n",
- rs.getString("BIL_ID"), rs.getString("BIL_DATE"), rs.getString("BIL_TITRE"), rs.getString("BIL_CONTENU"));*/
- System.out.println(
- rs.getString("BIL_ID") + (" ") + rs.getString("BIL_DATE") + (" ") + rs.getString("BIL_TITRE") + (" ") + rs.getString("BIL_CONTENU"));
- }
- } finally {
- // close result, statement and connection
- if (connect != null) connect.close();
- }
- }
- // programme principal
- public static void main(String[] Args)
- {
- JdbcSample test = new JdbcSample();
- try
- {
- test.loadDriver();
- test.listMonBlog();
- }
- catch (ClassNotFoundException e)
- {
- System.err.println("Pilote JDBC introuvable !");
- }
- catch (SQLException e)
- {
- System.out.println("SQLException: " + e.getMessage());
- System.out.println("SQLState: " + e.getSQLState());
- System.out.println("VendorError: " + e.getErrorCode());
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement