⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connectionexample.java

📁 JDBC数据库连接经典例子
💻 JAVA
字号:
package com.regular.test;

//-----------------------------------------------------------------------------
//ConnectionExample.java
//-----------------------------------------------------------------------------

/*
* =============================================================================
* Copyright (c) 1998-2007 Jeffrey M. Hunter. All rights reserved.
* 
* All source code and material located at the Internet address of
* http://www.idevelopment.info is the copyright of Jeffrey M. Hunter and
* is protected under copyright laws of the United States. This source code may
* not be hosted on any other site without my express, prior, written
* permission. Application to host any of the material elsewhere can be made by
* contacting me at jhunter@idevelopment.info.
*
* I have made every effort and taken great care in making sure that the source
* code and other content included on my web site is technically accurate, but I
* disclaim any and all responsibility for any loss, damage or destruction of
* data or any other property which may arise from relying on it. I will in no
* case be liable for any monetary damages arising from such loss, damage or
* destruction.
* 
* As with any code, ensure to test this code in a development environment 
* before attempting to run it in production.
* =============================================================================
*/

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;



public class ConnectionExample {

 final String driverClass        = "com.mysql.jdbc.Driver";
 final String connectionURL      = "jdbc:mysql://127.0.0.1/testdb?useUnicode=true&characterEncoding=utf-8";
 final String userID             = "root";
 final String userPassword       = "root";
 final String queryString        = "SELECT" +
                                   " * " +
                                   "FROM ne";

 /**
  * The following method provides an example of how to connect to a database
  * by registering the JDBC driver using the DriverManager class. This method
  * requires you to hardcode the loading of a Driver implementation in
  * your application. this alternative is the least desirable since it
  * requires a rewrite and recompile if your database or database driver
  * changes.
  */
 public void driverManager() {

     Connection con = null;
     Statement stmt = null;
     ResultSet rset = null;

     try {

         System.out.print("\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("| USING DriverManager CLASS     |\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("\n");

         System.out.print("  Loading JDBC Driver  -> " + driverClass + "\n");
         DriverManager.registerDriver(new com.mysql.jdbc.Driver());

         System.out.print("  Connecting to        -> " + connectionURL + "\n");
         con = DriverManager.getConnection(connectionURL, userID, userPassword);
         System.out.print("  Connected as         -> " + userID + "\n");

         System.out.print("  Creating Statement...\n");
         stmt = con.createStatement ();

         System.out.print("  Opening ResultsSet...\n");
         rset = stmt.executeQuery(queryString);

         while (rset.next()) {
             System.out.println("  Results...");
             System.out.println("      neid             -> " + rset.getString(2));
             System.out.println("      nename          -> " + rset.getString(3));
         }

         System.out.print("  Closing ResultSet...\n");
         rset.close();

         System.out.print("  Closing Statement...\n");
         stmt.close();

     } catch (SQLException e) {

         e.printStackTrace();
 
         if (con != null) {
             try {
                 con.rollback();
             } catch (SQLException e1) {
                 e1.printStackTrace();
             }
         }

     } finally {

         if (con != null) {
             try {
                 System.out.print("  Closing down all connections...\n\n");
                 con.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

     }

 }


 /**
  * The following method provides an example of how to connect to a database
  * by registering the JDBC driver using the jdbc.drivers property. The
  * DriverManager will load all classes listed in this property
  * automatically. This alternative works well for applications with a 
  * command-line interface, but might not be so useful in GUI applications
  * and applets. This is because you can specify properties at the command
  * line.
  */
 public void jdbcDriversProperty() {

     Connection con = null;
     Statement stmt = null;
     ResultSet rset = null;

     try {

         System.out.print("\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("| USING jdbc.drivers PROPERTY   |\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("\n");

         System.out.print("  Loading JDBC Driver  -> " + driverClass + "\n");
         System.setProperty("jdbc.drivers", driverClass);

         System.out.print("  Connecting to        -> " + connectionURL + "\n");
         con = DriverManager.getConnection(connectionURL, userID, userPassword);
         System.out.print("  Connected as         -> " + userID + "\n");

         System.out.print("  Creating Statement...\n");
         stmt = con.createStatement ();

         System.out.print("  Opening ResultsSet...\n");
         rset = stmt.executeQuery(queryString);

         while (rset.next()) {
             System.out.println("  Results...");
             System.out.println("      neid             -> " + rset.getString(2));
             System.out.println("      nename          -> " + rset.getString(3));
         }

         System.out.print("  Closing ResultSet...\n");
         rset.close();

         System.out.print("  Closing Statement...\n");
         stmt.close();

     } catch (SQLException e) {

         e.printStackTrace();

         if (con != null) {
             try {
                 con.rollback();
             } catch (SQLException e1) {
                 e1.printStackTrace();
             }
         }


     } finally {

         if (con != null) {
             try {
                 System.out.print("  Closing down all connections...\n\n");
                 con.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

     }

 }


 /**
  * The following method provides an example of how to connect to a database
  * by registering the JDBC driver using the Class.forName() method. This
  * complex expression is a tool for dynamically creating an instance of
  * a class when you have some variable representing the class name. Because
  * a JDBC driver is required to register itself whenever its static
  * initializer is called, this expression has the net effect of registering
  * your driver for you. 
  *
  *      NOTE: When using Class.forName("classname"), the JVM is supposed to
  *            be sufficient. Unfortunately, some Java virtual machines do
  *            not actuall call the static intitializer until an instance of
  *            a class is created. As a result, newInstance() should be 
  *            called to guarantee that the static initializer is run for
  *            all virtual machines.
  *
  * This method is by far the BEST in that it does not require hardcoded 
  * class names and it runs well in all Java environments. In real-world
  * applications, you should use this method along with a properties file
  * from which you load the name of the driver.
  * 
  */
 public void classForName() {

     Connection con = null;
     Statement stmt = null;
     ResultSet rset = null;
         
     try {

         System.out.print("\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("| USING Class.forName()         |\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("\n");


         System.out.print("  Loading JDBC Driver  -> " + driverClass + "\n");
         Class.forName(driverClass).newInstance();

         System.out.print("  Connecting to        -> " + connectionURL + "\n");
         con = DriverManager.getConnection(connectionURL, userID, userPassword);
         System.out.print("  Connected as         -> " + userID + "\n");

         System.out.print("  Creating Statement...\n");
         stmt = con.createStatement ();

         System.out.print("  Opening ResultsSet...\n");
         rset = stmt.executeQuery(queryString);

         while (rset.next()) {
             System.out.println("  Results...");
             System.out.println("      neid             -> " + rset.getString(2));
             System.out.println("      nename          -> " + rset.getString(3));
         }

         System.out.print("  Closing ResultSet...\n");
         rset.close();

         System.out.print("  Closing Statement...\n");
         stmt.close();

     } catch (ClassNotFoundException e) {

         e.printStackTrace();
     
     } catch (InstantiationException e) {

         e.printStackTrace();

     } catch (IllegalAccessException e) {

         e.printStackTrace();

     } catch (SQLException e) {

         e.printStackTrace();

         if (con != null) {
             try {
                 con.rollback();
             } catch (SQLException e1) {
                 e1.printStackTrace();
             }
         }

     } finally {

         if (con != null) {
             try {
                 System.out.print("  Closing down all connections...\n\n");
                 con.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

     }

 }


 /**
  * The following method provides an example of how to connect to a database
  * using the OCI JDBC Driver.
  * 
  */
 public void jdbcOCIDriver() {

     Connection con = null;
     Statement stmt = null;
     ResultSet rset = null;
         
     try {

         System.out.print("\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("| USING OCI Driver              |\n");
         System.out.print("+-------------------------------+\n");
         System.out.print("\n");


         System.out.print("  Loading JDBC Driver  -> " + driverClass + "\n");
         Class.forName(driverClass).newInstance();

         System.out.print("  Connecting to        -> " + connectionURL + "\n");
         con = DriverManager.getConnection(connectionURL, userID, userPassword);
         System.out.print("  Connected as         -> " + userID + "\n");

         System.out.print("  Creating Statement...\n");
         stmt = con.createStatement ();

         System.out.print("  Opening ResultsSet...\n");
         rset = stmt.executeQuery(queryString);

         while (rset.next()) {
             System.out.println("  Results...");
             System.out.println("      neid             -> " + rset.getString(2));
             System.out.println("      nename          -> " + rset.getString(3));
         }

         System.out.print("  Closing ResultSet...\n");
         rset.close();

         System.out.print("  Closing Statement...\n");
         stmt.close();

     } catch (ClassNotFoundException e) {

         e.printStackTrace();
     
     } catch (InstantiationException e) {

         e.printStackTrace();

     } catch (IllegalAccessException e) {

         e.printStackTrace();

     } catch (SQLException e) {

         e.printStackTrace();

         if (con != null) {
             try {
                 con.rollback();
             } catch (SQLException e1) {
                 e1.printStackTrace();
             }
         }

     } finally {

         if (con != null) {
             try {
                 System.out.print("  Closing down all connections...\n\n");
                 con.close();
             } catch (SQLException e) {
                 e.printStackTrace();
             }
         }

     }

 }


 /**
  * Sole entry point to the class and application.
  * @param args Array of String arguments.
  * @exception java.lang.InterruptedException
  *            Thrown from the Thread class.
  */
 public static void main(String[] args)
         throws java.lang.InterruptedException {

     ConnectionExample conExample = new ConnectionExample();

     conExample.classForName();

     Thread.sleep(5000);
     
     conExample.jdbcDriversProperty();

     Thread.sleep(5000);
     
     conExample.driverManager();
     
     Thread.sleep(5000);
     
 }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -