Advertisement
Guest User

Untitled

a guest
Feb 16th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1.  
  2. import java.sql.DriverManager; // gestion des pilotes
  3. import java.sql.Connection; // une connexion `a la BD
  4. import java.sql.Statement; // une instruction
  5. import java.sql.ResultSet; // un r´esultat (lignes/colonnes)
  6. import java.sql.SQLException; // une erreur
  7.  
  8.  
  9. public class JdbcSample {
  10. // chargement du pilote
  11. private String driverName = "com.mysql.jdbc.Driver";
  12.  
  13. public void loadDriver() throws ClassNotFoundException
  14. {
  15. Class.forName(driverName);
  16. }
  17.  
  18. // ouverture de connexion
  19. private String url = "jdbc:mysql://localhost/mon_blog";
  20. private String user = "ts2";
  21. private String password = "ts2";
  22.  
  23.  
  24. public Connection newConnection() throws SQLException {
  25. Connection connect = DriverManager.getConnection(url, user, password);
  26. return connect;
  27. }
  28.  
  29. // execution d’une requete
  30. final String monblog = "SELECT BIL_ID, BIL_DATE, BIL_TITRE, BIL_CONTENU FROM t_billet;";
  31.  
  32. public void listMonBlog() throws SQLException {
  33. Connection connect = null;
  34. try {
  35. // create new connection and statement
  36. connect = newConnection();
  37. Statement st = connect.createStatement();
  38. ResultSet rs = st.executeQuery(monblog);
  39. while (rs.next()) {
  40.  
  41. /*System.out.printf("%-20s | %-20s | %3d\n",
  42. rs.getString("BIL_ID"), rs.getString("BIL_DATE"), rs.getString("BIL_TITRE"), rs.getString("BIL_CONTENU"));*/
  43.  
  44. System.out.println(
  45. rs.getString("BIL_ID") + (" ") + rs.getString("BIL_DATE") + (" ") + rs.getString("BIL_TITRE") + (" ") + rs.getString("BIL_CONTENU"));
  46. }
  47. } finally {
  48. // close result, statement and connection
  49. if (connect != null) connect.close();
  50. }
  51. }
  52.  
  53. // programme principal
  54. public static void main(String[] Args)
  55. {
  56. JdbcSample test = new JdbcSample();
  57. try
  58. {
  59. test.loadDriver();
  60. test.listMonBlog();
  61. }
  62.  
  63. catch (ClassNotFoundException e)
  64. {
  65. System.err.println("Pilote JDBC introuvable !");
  66. }
  67.  
  68. catch (SQLException e)
  69. {
  70. System.out.println("SQLException: " + e.getMessage());
  71. System.out.println("SQLState: " + e.getSQLState());
  72. System.out.println("VendorError: " + e.getErrorCode());
  73. e.printStackTrace();
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement