Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. /*
  2. * A MySQL SHOW DATABASE example using Java
  3. * @author mysqlcommands.com
  4. */
  5.  
  6. //STEP 1. Import required packages
  7. import java.sql.*;
  8. import java.util.List;
  9.  
  10. public class JDBCExample {
  11. // JDBC driver name and database URL
  12.  
  13. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  14. static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
  15.  
  16. // Database credentials
  17. static final String USER = "username";
  18. static final String PASS = "password";
  19.  
  20. public static void main(String[] args) {
  21. Connection conn = null;
  22. Statement stmt = null;
  23. try {
  24. //STEP 2: Register JDBC driver
  25. Class.forName("com.mysql.jdbc.Driver");
  26.  
  27. //STEP 3: Open a connection
  28. System.out.println("Connecting to a selected database...");
  29. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  30. System.out.println("Connected database successfully...");
  31.  
  32. //STEP 4: Execute a query
  33. ResultSet rs;
  34. stmt = conn.createStatement();
  35. String sql = "SHOW DATABASES";
  36. stmt.executeUpdate(sql);
  37. rs = stmt.executeQuery(sql);
  38. //Print out results
  39. while (rs.next()) {
  40. System.out.println(rs.getString("TABLE_CAT"));
  41. }
  42. } catch (SQLException se) {
  43. //Handle errors for JDBC
  44. se.printStackTrace();
  45. } catch (Exception e) {
  46. //Handle errors for Class.forName
  47. e.printStackTrace();
  48. } finally {
  49. //finally block used to close resources
  50. try {
  51. if (stmt != null) {
  52. conn.close();
  53. }
  54. } catch (SQLException se) {
  55. }// do nothing
  56. try {
  57. if (conn != null) {
  58. conn.close();
  59. }
  60. } catch (SQLException se) {
  61. se.printStackTrace();
  62. }//end finally try
  63. }//end try
  64. System.out.println("Goodbye!");
  65. }//end main
  66. }//end JDBCExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement