好久没碰JAVA了,都忘了该怎么连接数据库了

解决方案 »

  1.   

    JDBC 编程的步骤
            import java.sql.*;
        0.参数化
            String driverName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/test"; //协议;库或服务器名称;服务器IP,端口
            String username = "root";
            String password="";
                /* Oracle的连接
                String driverName = "oracle.jdbc.driver.OracleDriver";
                String url = "jdbc:oracle:thin:@192.168.0.23:1521:ora10g"; 
                String username = "openlab";
                String password="open123";*/
            //以下这些都需要写在有异常的代码块里,所以需要提取出来。
            Connection conn = null;
            Statement stmt = null;
            ResultSet rs = null;//建议用PreparedStatement
        1.加载和注册数据库驱动
            Class.forName(driverName);//自动注册;需要把驱动的jar包导进来;需处理异常
                /*方法二:实例化具体的Driver驱动,这写法一般不用(不能参数化驱动名,不够灵活)
                Driver driver = new com.mysql.jdbc.Driver();
                DriverManager.registerDriver(driver); //将驱动交于DriverManager托管*/
                /*方法三:Dos运行时,java -Djdbc.drives = oracle.jdbc.driver.OracleDriver; --可多个 */
        2.连接数据库
            conn = DriverManager.getConnection(url, username, password);//需处理异常
            //Connection返回数据库连接,如:“com.mysql.jdbc.Connection@1ffb8dc”;连接不成功则返回 null
        3.创建Statement对象 //为了类型安全和批量更新的效率,改用PreparedStatement
            stmt = conn.createStatement();//需处理异常
            //返回其生成结果的对象"oracle.jdbc.driver.OracleStatement@198dfaf"
        4.操作数据库,执行SQL语句
            String sql = "select * from tableName";//SQL语句里不需要写分号
            rs = stmt.executeQuery(sql); //executeQuery(sqlString) 查询 返回查询结果集
                /* String sql = "insert into tableName values(?,?)"; // ?占位符
                int number = stmt.executeUpdate(sql);//更新,再返回int(更新、修改影响的条数) */
        5.处理数据(游标) 
            StringBuffer sb = new StringBuffer(); //缓存;用它可提高读取速度。当然,不用也可以。
            ResultSetMetaData md = rs.getMetaData(); //ResultSetMetaData可获取列的类型和属性信息
            int col = md.getColumnCount(); //获取列的数目
            while(rs.next()){ //rs.next()使游标下移一位,返回boolean,没有下一个结果则返回false
                for(int i=1; i<=col;i++){ // index(JDBC 的下标从1开始)  
                    sb.append(md.getColumnName(i)+"="+rs.getString(i)+"  ");
                } sb.append("\n");
            }System.out.println(sb);
                //1.游标的初始位置在第一条记录的前面,使第一次调用next()后,刚好拿到第一个结果。
                //2.游标的最终位置在最后一条记录的后面(结果集的前面和后面留空,真正存在) 
        6.释放资源,断开与数据库的连接
            //先判断是否有引用资源,再释放(释放空资源会抛异常);注意顺序
            if(rs!=null)try{rs.close();}catch(Exception e){e.printStackTrace();}
            if(stmt!=null)try{stmt.close();}catch(Exception e){e.printStackTrace();}
            if(conn!=null)try{conn.close();}catch(Exception e){e.printStackTrace();}
            //这些异常没法处理,处理只为方便调试。所以这些异常处理也只是打印。
            /*要按先ResultSet结果集,后Statement,最后Connection的顺序关闭资源,
            因为ResultSet需要Statement和Connection连接时才可以用的;Statement也需要Connection才可用;
            结束Statement之后有可能其它的Statement还需要连接,因此不能先关闭Connection。ResultSet同理。*/ 
      

  2.   

    ..你想用配置文件管理连数据库?
    <?xml version="1.0" encoding="UTF-8"?><jdbc>
    <!--
    <url>jdbc:oracle:thin:@192.168.0.26:1521:tarena</url>
    <driver>oracle.jdbc.driver.OracleDriver</driver>
    <username>sd1010</username>
    <password>sd1010</password>
    -->
    <url>jdbc:mysql://localhost:3306/test</url>
    <driver>com.mysql.jdbc.Driver</driver>
    <username>root</username>
    <password></password>
    <dbcp>
    <initialSize>2</initialSize>
    <maxActive>5</maxActive>
    <maxIdle>2</maxIdle>
    <maxWait>300000</maxWait>
    <validationQuery>select now()</validationQuery>
    </dbcp>
    </jdbc>
    配置文件
    package day01;import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;import org.dom4j.Document;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;public class Configuration { private String url; private String driver; private String uesrname; private String password; private int initialSize; private int maxActive; private int maxIdle; private long maxWait; private String validationQuery; public Configuration() { } public Configuration(String url, String driver, String uesrname,
    String password) {
    super();
    this.url = url;
    this.driver = driver;
    this.uesrname = uesrname;
    this.password = password;
    } public String getDriver() {
    return driver;
    } public void setDriver(String driver) {
    this.driver = driver;
    } public String getPassword() {
    return password;
    } public void setPassword(String password) {
    this.password = password;
    } public String getUesrname() {
    return uesrname;
    } public void setUesrname(String uesrname) {
    this.uesrname = uesrname;
    } public String getUrl() {
    return url;
    } public void setUrl(String url) {
    this.url = url;
    } public int getInitialSize() {
    return initialSize;
    } public void setInitialSize(int initialSize) {
    this.initialSize = initialSize;
    } public int getMaxActive() {
    return maxActive;
    } public void setMaxActive(int maxActive) {
    this.maxActive = maxActive;
    } public int getMaxIdle() {
    return maxIdle;
    } public void setMaxIdle(int maxIdle) {
    this.maxIdle = maxIdle;
    } public long getMaxWait() {
    return maxWait;
    } public void setMaxWait(long maxWait) {
    this.maxWait = maxWait;
    } public String getValidationQuery() {
    return validationQuery;
    } public void setValidationQuery(String validationQuery) {
    this.validationQuery = validationQuery;
    } /*
     * 读取配置文件 生成configuration对象 默认配置文件是类路径中的jdbc.xml
     */
    public static Configuration configure() {
    try {
    InputStream in = Configuration.class
    .getResourceAsStream("/jdbc.xml");
    Configuration cfg = load(in); return cfg;
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    } public static Configuration configure(File file) {
    try {
    InputStream in = new FileInputStream(file);
    Configuration cfg = load(in); return cfg;
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    } } private static Configuration load(InputStream in) throws Exception {
    SAXReader reader = new SAXReader();
    Document doc = reader.read(in);
    Element jdbc = doc.getRootElement();
    String url = jdbc.element("url").getText();
    String username = jdbc.element("username").getText();
    String driver = jdbc.element("driver").getText();
    String password = jdbc.element("password").getText(); Configuration cfg = new Configuration(url, driver, username, password);
    Element dbcp = jdbc.element("dbcp");
    cfg.setInitialSize(Integer.parseInt(dbcp.element("initialSize")
    .getText()));
    cfg.setMaxActive(Integer.parseInt(dbcp.element("maxActive").getText()));
    cfg.setMaxIdle(Integer.parseInt(dbcp.element("maxIdle").getText()));
    cfg.setMaxWait(Long.parseLong(dbcp.element("maxWait").getText()));
    cfg.setValidationQuery(dbcp.element("validationQuery").getText());
    return cfg;
    } public static void main(String[] args) {
    Configuration cfg = Configuration.configure();
    System.out.println(cfg.getUrl());
    System.out.println(cfg.getDriver());
    System.out.println(cfg.getUesrname());
    System.out.println(cfg.getPassword());
    System.out.println(cfg.getInitialSize());
    System.out.println(cfg.getMaxActive());
    System.out.println(cfg.getMaxIdle());
    System.out.println(cfg.getMaxWait());
    System.out.println(cfg.getValidationQuery());
    }}
    读配置文件
    package day01;import java.sql.Connection;import java.sql.ResultSet;
    import java.sql.Statement;import org.apache.commons.dbcp.BasicDataSource;public class DBUtil { /**
     * @param args
     */
    private static Configuration cfg = Configuration.configure();// 加载配置信息 private static ThreadLocal<Connection> threadlocal = new ThreadLocal<Connection>(); private static BasicDataSource ds = new BasicDataSource();// dbcp连接池
    static {
    try {
    // Class.forName(cfg.getDriver());//注册驱动
    ds.setUrl(cfg.getUrl());
    ds.setDriverClassName(cfg.getDriver());
    ds.setUsername(cfg.getUesrname());
    ds.setPassword(cfg.getPassword()); ds.setInitialSize(cfg.getInitialSize());// 初始容量
    ds.setMaxActive(cfg.getMaxActive());// 最大连接数
    ds.setMinIdle(cfg.getMaxIdle());// 最大空闲数
    ds.setMaxWait(cfg.getMaxIdle());// 最大等待时间
    ds.setValidationQuery(cfg.getValidationQuery());// 验证的sql语句
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    } public static Connection open() throws Exception {
    // return DriverManager.getConnection(cfg.getUrl(), cfg.getUesrname(),
    // cfg
    // .getPassword());//返回Connection
    return ds.getConnection(); } public static void close(Connection con, Statement stmt, ResultSet rs) {
    try {
    if (null != rs) {
    rs.close();
    }
    } catch (Exception e) {
    }
    try {
    if (null != stmt) {
    stmt.close();
    }
    } catch (Exception e) {
    }
    try {
    if (null != con) {
    con.close();
    }
    } catch (Exception e) {
    }
    } public static void main(String[] args) throws Exception {
    Connection con = DBUtil.open();
    System.out.println(con);
    DBUtil.close(con, null, null);
    } public static Connection openInThread() throws Exception { Connection con = threadlocal.get();
    if (null == con) {
    con = open();
    threadlocal.set(con);
    }
    return con;
    } public static void closeInThread() {
    Connection con = threadlocal.get();
    if (null != con) {
    try {
    con.close();
    } catch (Exception e) {

    }
    threadlocal.remove();
    }
    }
    }
    获取连接...