首页 > 代码库 > JDBC

JDBC

 

 

Code Example

Driver: mysql-connector-java

 1 /** 2  * Created by artificerPi on 2016/2/23. 3  * JDBC Program, create database 4  * 5  */ 6  7 // STEP 1. Import required packages 8 import java.sql.*; 9 10 public class JDBCExample {11     // JDBC driver name and database URL12     static final String JDBC_DRIVER="com.mysql.jdbc.Driver";13     static final String DB_URL="jdbc:mysql://localhost";14 15     // Database credentials16     static final String USER ="root";17     static final String PASS="passw0rd";18 19     public static void main(String[] args){20         Connection conn = null;21         Statement stmt = null;22 23         try{24             //STEP2 : Register JDBC driver25             Class.forName(JDBC_DRIVER);26 27             //STEP3 : Open a connection28             System.out.println("Connecting to database...");29             conn = DriverManager.getConnection(DB_URL,USER,PASS);30 31             // STEP 4: Execute a query32             System.out.println("Creating statement ...");33             stmt = conn.createStatement();34 35             String sql;36             sql="CREATE DATABASE STUDENTS";37             stmt.executeUpdate(sql);38             System.out.println("Database created successfully...");39         }catch(SQLException se){40             //Handle errors for JDBC41             se.printStackTrace();42         }catch (Exception e){43             // Handle errors for Class.forName44             e.printStackTrace();45         }finally {46             // finally block used to close resources47             try{48                 if (stmt != null)49                     stmt.close();50             }catch (SQLException se2){// nothing we can do51             }try{52                 if(conn!=null)53                     conn.close();54             }catch (SQLException se){55                 se.printStackTrace();56             }// end finally try57         }// end try58         System.out.println("GoodBye!");59     }//end main60 }// end FirstExample

 

JDBC