Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2536698
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-27 14:59:34

这个例子主要介绍jdbc连接mysql数据库。

step 1: 下载MySQL JDBC Driver
下载地址:MySQL JDBC Driver Download Here

step 2: java JDBC连接mysql实例

jdbc连接mysql的代码:
  1. Class.forName("com.mysql.jdbc.Driver");
  2.   Connection connection = null;
  3.   connection = DriverManager.getConnection(
  4.           "jdbc:mysql://hostname:port/dbname","username", "password");
  5.   connection.close();

查看一个完整的实例:
(记得引入step 1 下载的driver: mysql-connector-java-x.x.x-bin.jar)
文件: JDBCConnectMySQL.java

  1. package org.hnrsc.jdbc;

  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;

  5. public class JDBCConnectMySQL {

  6.     /**
  7.      * @param args
  8.      */
  9.     public static void main(String[] args) {
  10.         System.out.println("-------- MySQL JDBC Connection Testing ------------");
  11.         try{
  12.             Class.forName("com.mysql.jdbc.Driver");
  13.         }catch(ClassNotFoundException e){
  14.             System.out.println("Can't find the MySQL JDBC Driver");
  15.             e.printStackTrace();
  16.             return;
  17.         }
  18.         
  19.         System.out.println("MySQL JDBC Driver Registered!");
  20.         Connection conn = null;
  21.         
  22.         try{
  23.             conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "");
  24.         }catch(SQLException e){
  25.             System.out.println("Connection Failed! Check output console");
  26.             e.printStackTrace();
  27.             return;
  28.         }
  29.         
  30.         if (conn != null) {
  31.             System.out.println("You made it, take control your database now!");
  32.         } else {
  33.             System.out.println("Failed to make connection!");
  34.         }
  35.     }

  36. }

step 3:运行
你可能会看到以下结果:
  1. -------- MySQL JDBC Connection Testing ------------
  2. MySQL JDBC Driver
  3. You made it, take control your database


阅读(986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~