Advertisement
Guest User

Codigo ejemplo

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