一个简单的java jdbc案例

有些时候,配置一个spring+mybatis框架,然后写xml,dao ,service显得特别繁琐。

如果我们只是想查一下数据库,不考虑连接复用也不考虑动态sql,可以用原生的jdbc来实现,方便快捷,也有利于认识原生jdbc。

我们需要的东西其实不多:

一个数据库连接的配置文件(甚至这个也可以不需要),

db.properties

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@ip:port:sid
user=username
password=pwd

一个class

import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by tm on 2016/12/16.
 */
public class Test {

    /**
     * 初始化数据库,加载驱动。
     * 调用方法
     * @param args
     */
    public static void main(String[] args) {
        DbConfig.initDriver();
        Map<String,Object> data = new HashMap<String, Object>();
        Test test = new Test();
        System.out.println(test.updateState(data));
    }

    /**
     * 更新某个状态
     * @param data
     * @return
     */
    public boolean updateState(Map<String, Object> data) {
        Connection conn = null;
        boolean flag = false;
        try {
            String sql = "update table set a=?,b=? ";
            conn = DriverManager.getConnection(dbConfig.url, dbConfig.user, dbConfig.password);
            PreparedStatement state = conn.prepareStatement(sql);
            state.setInt(1,1);
            state.setString(2,"2");
            int count = state.executeUpdate();
            if(count>0){
                flag = true;
            }
            conn.commit();
            state.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 静态内部类,初始化之后就一直存在不会随对象变化。
     * 持有数据库信息
     */
    static class DbConfig{
        static String url;
        static String user;
        static String password;

        /**
         * init db driver
         */
        public static void initDriver() {
            Properties props = new Properties();
            {
                try {
                    props.load(dbConfig.class.getClassLoader().getResourceAsStream("db.properties"));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.exit(-1);
                }
            }

            String driver = props.getProperty("driver");
            try {
                Class.forName(driver);
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.exit(-1);
            }

            dbConfig.url = props.getProperty("url");
            dbConfig.user = props.getProperty("user");
            dbConfig.password = props.getProperty("password");
        }
    }
}

数据库驱动ojdbc6、或者mysql驱动。

当然,以上只是非常简单的用法,不考虑任何的扩展性重用性之类的。

如果有稍微多一点的需求,就最好自己写个dao。如果再多一点的需求就考虑使用框架了。

贴一个简单的连接管理工具,DBUtil

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * 负责管理数据库连接
 * @author TM
 *
 */
public class DBUtil {
	//连接池
	private static BasicDataSource cp;
	
	static{
		/*
		 * 初始化静态属性!
		 * 静态块由于是在类第一次加载时执行
		 * 并且只会执行一次,所以在这里初始化静态属性是
		 * 最适合的地方。
		 */
		//java.util.properties
		Properties prop =new Properties();
		try {
			prop.load(new FileInputStream("config.properties"));
			//根据配置项初始化
			String driverName=prop.getProperty("driverName");
			String url=prop.getProperty("url");
			String username=prop.getProperty("username");
			String password=prop.getProperty("password");
			//最大连接数
			int maxActive=Integer.parseInt(prop.getProperty("maxActive"));
			//最大等待时间
			int maxWait=Integer.parseInt(prop.getProperty("maxWait"));
			
			System.out.println(driverName+"
"+url+"
"+username+"
"+password);
			System.out.println(maxActive+"
"+maxWait);
			//初始化连接池
			cp=new BasicDataSource();
			//相当于Class.forName()中的内容
			cp.setDriverClassName(driverName);
			cp.setUrl(url);
			cp.setUsername(username);
			cp.setPassword(password);
			cp.setMaxActive(maxActive);
			cp.setMaxWait(maxWait);
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取一个数据库连接
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception{
		/*
		 * 向连接池要一条可用的空闲连接
		 * 若连接池尚有可用连接,会直接返回
		 * 若没有,则该方法进入阻塞状态,等待可用连接
		 * 等待的时间(就是初始化连接池时设置的maxWait)
		 * 与初始化连接池时设置的maxWait的时间一致
		 * 若等待的时间内出现可用的空闲连接
		 * 则该方法会立刻返回该连接,若等待的时间超过maxWait后
		 * 仍然没有获得可用连接,该方法会抛出超时异常。
		 */
		return cp.getConnection();
	}
	
	/**
	 * 将给定的数据库连接关闭
	 * @param conn
	 */
	public static void closeConnection(Connection conn){
		try{
			if(conn!=null){
				//只是还给了连接池了。
				conn.close();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
	}
	
	public static void main(String[] args) throws Exception{
		Connection conn=DBUtil.getConnection();
	}
}

  

原文地址:https://www.cnblogs.com/opensesame/p/6410690.html