JDBC工具类

//在src下创建dbinfo.properties(/JDBDTest/src/dbinfo.properties)

className=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb2
user=root
password=root

///JDBDTest/src/com/huowolf/util/JdbcUtil.java

package com.huowolf.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
	private static String className;
	private static String url;
	private static String user;
	private static String password;
	static{
		try {
			InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("dbinfo.properties");
			Properties props = new Properties();
			props.load(in);
			className = props.getProperty("className");
			url = props.getProperty("url");
			user = props.getProperty("user");
			password = props.getProperty("password");
			Class.forName(className);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() throws Exception{
		return DriverManager.getConnection(url, user, password);	
	}
	
	public static void release(ResultSet rs,Statement stmt,Connection conn){
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			if(stmt!=null)
				stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}


}
//测试类

package com.huowolf;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import com.huowolf.util.JdbcUtil;

public class JdbcDemo {
	
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtil.getConnection();
			stmt = conn.createStatement();
			rs = stmt
					.executeQuery("select id,name,password,email,birthday from users");
			while (rs.next()) {
				System.out.println("------------------------");
				System.out.println(rs.getObject("id"));
				System.out.println(rs.getObject("name"));
				System.out.println(rs.getObject("password"));
				System.out.println(rs.getObject("email"));
				System.out.println(rs.getObject("birthday"));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtil.release(rs, stmt, conn);
		}

	}

}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。