日期:2014-05-20 浏览次数:20698 次
package lin.test; import java.sql.*; public class Test { public static void main(String[] args) { //驱动程序名 String driveName = "com.mysql.jdbc.Driver"; //URL指向要访问的数据库名test String databaseURL = "jdbc:mysql://localhost:3306/test"; //MySQL配置时的用户名 String user = "root"; //MySQL配置时的密码 String password = "root";// 此处写自己的密码 try { //加载驱动 Class.forName(driveName); System.out.println("成功加载数据库驱动程序"); } catch (java.lang.ClassNotFoundException e) { System.out.println("加载数据库驱动程序失败"); System.out.println("加载数据库驱动程序失败"); System.out.println(e.getMessage()); return; } try { /连续MySQL数据库 Connection con = DriverManager.getConnection(databaseURL, user,password); System.out.println("连接数据库成功"); //关闭连接 con.close(); } catch (SQLException e) { System.out.println("连接数据库失败"); System.out.println("SQLException:" + e.getMessage()); return; } } }
/ * When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by doing Class.forName("foo.bah.Driver") */ package com.mysql.jdbc; import java.sql.SQLException; public class Driver extends NonRegisteringDriver implements java.sql.Driver { // ~ Static fields/initializers // --------------------------------------------- // // Register ourselves with the DriverManager // static { try { java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } } // ~ Constructors // ----------------------- /** * Construct a new driver and register it with DriverManager * * @throws SQLException * if a database error occurs. */ public Driver() throws SQLException { // Required for Class.forName().newInstance() } }