您的位置:首页 > 数据库

JDBC连接各种数据库的方法

2012-07-07 18:39 316 查看
JDBC连接各种数据库

模板代码:

package com.cazi.jdbc.util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

/**

 * @author HuangYucai

 */

public class JDBCCommon {

 /**

  * 数据库连的信息

  */

 private static String driver_Class = "";

 private static String url = "";

 private static String password = "";

 private static String username = "";

 private static Connection conn = null;

 //静态块中获取连接

 static {

  try {

   Class.forName(driver_Class);

  } catch (Exception e) {

   throw new RuntimeException(e);

  }

 }

 

 /**

  * 获取数据库连接

  * @return

  */

 public static Connection getConnection() {

  try {

   conn = DriverManager.getConnection(url, password, username);

  } catch (Exception e) {

   throw new RuntimeException(e);

  }

  return conn;

 }

 /**

  * 关闭数据库连接

  * @return

  */

 public static void closeConnection(ResultSet rs, Statement stmt,

   Connection conn) {

  try {

   if (rs != null) {

    rs.close();

   }

  } catch (SQLException rse) {

   throw new RuntimeException(rse);

  } finally {

   try {

    if (stmt != null) {

     stmt.close();

    }

   } catch (SQLException ste) {

    throw new RuntimeException(ste);

   } finally {

    try {

     if (conn != null) {

      conn.close();

     }

    } catch (SQLException cne) {

     throw new RuntimeException(cne);

    }

   }

  }

 }

}

 

1>JDBC连接MySQL

  a、导入mysql的jar包

 

  b、mysql的通用连接字符串:

 String driver_Class="com.mysql.jdbc.Driver";

 String url="jdbc:mysql://127.0.0.1:3306/dbName";

 String password="root";

 String username="root";

2>Oracle

  a、导入oracle的jar包

 

  b、oracle的通用连接字符串:

 String driver_Class="oracle.jdbc.OracleDriver";

 String url="jdbc:oracle:thin:@127.0.0.1:1521:dbName";

 String password=scott";

 String username="tiger";

3>SQLServer2005

  a、配置:开始->Miscrosoft SQLServer2005->配置工具->SQLServer配置管理器->MSSQLSERVER的协议->启用TCP/IP->属性配置IPALL的端口号为:1433

 

  b、导入sqlserver的jar包

 

  c、oracle的通用连接字符串:

 String driver_Class="com.microsoft.sqlserver.jdbc.SQLServerDriver";

 String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=dbName";

 String password="sa";

 String username="sa";

  

为了更大的理想,要活的更有意义。孤独,是因为我不够坚强,不够成熟。一切想要的,都不能争来,只能是赢来。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息