Advertisement
Guest User

Untitled

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