数据库连接JDBC工具类

这是我在连接数据库的时候,自己写的简单的数据库连接工具类,里面的几个常量其实本应放到枚举类中的,但是偷懒了,

放到这里希望可以帮到大家,以后也会继续完善。

package com.blueZhang;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class DBUtil {
	public static final int CONNECTION_SQLILT = 3;
	public static final int CONNECTION_MYSQL = 2;
	public static final int CONNECTION_SQL = 1;
	public static final int CONNECTION_ODBC = 0;

	public DBUtil() {
	}

	public static Connection getConnection(int connection_type)
			throws Exception {
		switch (connection_type) {
		case CONNECTION_ODBC:
			return getConnectionODBC();
		case CONNECTION_SQL:
			return getConnectionSQL();
		case CONNECTION_MYSQL:
			return getConnectionMYSQL();
		}
		return null;
	}

	/**
	 * 使用JDBC-ODBE连接
	 */
	private static Connection getConnectionODBC() throws Exception {
		Connection conn = null;
		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			System.out.println("abc");
			conn = DriverManager.getConnection("jdbc:odbc:mybook", "sa", "123");
			System.out.println("连接成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;
	}

	/**
	 * 使用JDBC驱动 连接
	 * 
	 * @throws Exception
	 * 
	 * */
	private static Connection getConnectionSQL() throws Exception {
		Connection conn = null;
		String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=user;";
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

			conn = DriverManager.getConnection(connectionUrl, "sa", "123");
			System.out.println("连接成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;
	}

	/**
	 * 使用jar包连接Mysql
	 * 
	 * 
	 * */
	private static Connection getConnectionMYSQL() throws Exception {
		String connectionUrl = "jdbc:mysql://localhost:3306/user";
		String username = "root";
		String password = "mysql";
		Connection conn = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");

			conn = DriverManager.getConnection(connectionUrl, username,
					password);
			System.out.println("连接成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;

	}
	
	
	/**
	 * 使用jar包连接SQlite
	 * 
	 * 
	 * */
	public static Connection getConnectionSQlite() throws Exception {

		Connection conn = null;// 连接数据库的对象
		try {
			Class.forName("org.sqlite.JDBC");// 通过反射,获取驱动程序
			// step2:提供链接的参数
			String url = "jdbc:sqlite:/c:/pro/test.db";
			// step3:动DriverManager中获取连接对象Connection
			conn = DriverManager.getConnection(url);
			System.out.println("连接成功");

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return conn;

	}

	public static void close(Connection conn) throws Exception {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw e;
			}
		}
	}

}


你可能感兴趣的:(sql,数据库,jdbc)