Advertisement
Guest User

Untitled

a guest
Nov 29th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. /*
  2. * A MySQL UPDATE example using Java
  3. * @author mysqlcommands.com
  4. */
  5.  
  6. //STEP 1. Import required packages
  7. //STEP 1. Import required packages
  8. import java.sql.*;
  9.  
  10. public class JDBCExample {
  11.  
  12. // JDBC driver name and database URL
  13. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  14. static final String DB_URL = "jdbc:mysql://localhost/";
  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 database...");
  29. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  30.  
  31. //STEP 4: Execute a query
  32. System.out.println("Creating database...");
  33. stmt = conn.createStatement();
  34.  
  35. String sql = "CREATE DATABASE STUDENTS";
  36. stmt.executeUpdate(sql);
  37. System.out.println("Database created successfully...");
  38. } catch (SQLException se) {
  39. //Handle errors for JDBC
  40. se.printStackTrace();
  41. } catch (Exception e) {
  42. //Handle errors for Class.forName
  43. e.printStackTrace();
  44. } finally {
  45. //finally block used to close resources
  46. try {
  47. if (stmt != null) {
  48. stmt.close();
  49. }
  50. } catch (SQLException se2) {
  51. }// nothing we can do
  52. try {
  53. if (conn != null) {
  54. conn.close();
  55. }
  56. } catch (SQLException se) {
  57. se.printStackTrace();
  58. }//end finally try
  59. }//end try
  60. System.out.println("Goodbye!");
  61. }//end main
  62. }//end JDBCExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement