码迷,mamicode.com
首页 > 数据库 > 详细

JDBC

时间:2016-10-02 19:29:08      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

 

 

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 URL
12     static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
13     static final String DB_URL="jdbc:mysql://localhost";
14 
15     // Database credentials
16     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 driver
25             Class.forName(JDBC_DRIVER);
26 
27             //STEP3 : 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 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 JDBC
41             se.printStackTrace();
42         }catch (Exception e){
43             // Handle errors for Class.forName
44             e.printStackTrace();
45         }finally {
46             // finally block used to close resources
47             try{
48                 if (stmt != null)
49                     stmt.close();
50             }catch (SQLException se2){// nothing we can do
51             }try{
52                 if(conn!=null)
53                     conn.close();
54             }catch (SQLException se){
55                 se.printStackTrace();
56             }// end finally try
57         }// end try
58         System.out.println("GoodBye!");
59     }//end main
60 }// end FirstExample

 

JDBC

标签:

原文地址:http://www.cnblogs.com/7explore-share/p/5927802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!