Guest User

Untitled

a guest
Oct 12th, 2016
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package CreateDatabase;
  2.  
  3. //STEP 1. Import required packages
  4. import java.sql.*;
  5.  
  6. public class CreateDatabase {
  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/EMPLOYEE";
  10. // Database credentials
  11. static final String USER = "root";
  12. static final String PASS = "student";
  13.  
  14. public static void main(String[] args) {
  15. Connection conn = null;
  16. Statement stmt = null;
  17. try {
  18. // STEP 2: Register JDBC driver
  19. Class.forName("com.mysql.jdbc.Driver");
  20. // STEP 3: Open a connection
  21. System.out.println("Connecting to database...");
  22. conn = DriverManager.getConnection(DB_URL, USER, PASS);
  23. // STEP 4: Execute a query
  24. System.out.println("Creating database...");
  25. stmt = conn.createStatement();
  26. String sql = "CREATE DATABASE IF NOT EXISTS EMPLOYEE";
  27. stmt.executeUpdate(sql);
  28. System.out.println("Database Created");
  29. sql = "CREATE TABLE IF NOT EXISTS EMP( NAME VARCHAR(20),REGNO CHAR(10),BRANCH VARCHAR(20),EMAIL VARCHAR(50));";
  30. stmt.executeUpdate(sql);
  31. System.out.println("Database created successfully...");
  32. sql = "INSERT INTO STUD VALUES('VENKAT','130911142','IT','venkatrajvanshi@gmail.com')";
  33. stmt.executeUpdate(sql);
  34. sql = "INSERT INTO STUD VALUES('SHUBHAM','130911152','IT','shubh95varma@yahoo.co.in')";
  35. stmt.executeUpdate(sql);
  36. sql = "INSERT INTO STUD VALUES('RISHABH','130911110','IT','indoria.rishabh5@gmail.com')";
  37. stmt.executeUpdate(sql);
  38. System.out.println("Values Entered!");
  39.  
  40. } catch (SQLException se) {
  41. // Handle errors for JDBC
  42. se.printStackTrace();
  43. } catch (Exception e) {
  44. // Handle errors for Class.forName
  45. e.printStackTrace();
  46. } finally {
  47. // finally block used to close resources
  48. try {
  49. if (stmt != null)
  50. stmt.close();
  51. } catch (SQLException se2) {
  52. }// nothing we can do
  53. try {
  54. if (conn != null)
  55. conn.close();
  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
Add Comment
Please, Sign In to add comment