자바 는 JDBC 를 통 해 데이터 베 이 스 를 연결 합 니 다.

2886 단어 jdbc
Connection 관리 코드:
package com.plugin.usermanagerplugin.util;

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

public class ConnectionUtil {

	/**
	 * 
	 *     :        .
	 * @author LYQ 2013-8-7   05:32:29
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 
	 *     :     
	 * @author LYQ 2013-8-7   05:38:41
	 * @param Connection conn
	 * @param PreparedStatement ps
	 * @param ResultSet rs
	 */
	public static void colseConnection(Connection conn, PreparedStatement ps, ResultSet rs) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
		
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			ps = null;
		}
		
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
	}
	
	/**
	 * 
	 *     :     
	 * @author LYQ 2013-8-8   09:52:15
	 * @param Connection conn
	 * @param PreparedStatement ps
	 */
	public static void colseConnection(Connection conn, PreparedStatement ps) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		conn = null;
		
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		ps = null;
	}
}

Dao 클래스:
	String sql = "select t.userid, t.username, from studio_userlist t where t.usercode = ? AND t.password = ?";
	Connection conn = ConnectionUtil.getConnection();
	PreparedStatement ps = null;
	ResultSet rs = null;
	try {
		ps = conn.prepareStatement(sql);
		ps.setString(1, text_userName);
		ps.setString(2, text_userPWD);
		rs = ps.executeQuery();
		UserBean user = new UserBean();
		if(rs.next()) {
			user.setId(rs.getString(1));
			user.setName(rs.getString(2));
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		ConnectionUtil.colseConnection(conn, ps, rs);
	}

JAVA 에서 자주 사용 하 는 데이터베이스 연결 문자열:
DriverClass: oracle.jdbc.driver.OracleDriver
Oracle 연결 문자열:
jdbc:oracle:thin:@127.0.0.1:1521:orcl
DriverClass:
com.microsoft.sqlserver.jdbc.SQLServerDriver
SQLServer 연결 문자열:
    jdbc:sqlserver://127.0.0.1:1433;database=dbname
DirverClass:
com.mysql.jdbc.Driver
MYSQL 연결 문자열:
jdbc:mysql://localhost:3306/test

좋은 웹페이지 즐겨찾기