JDBC:java数据库连接

来源:互联网 发布:马蓉面相 知乎 编辑:程序博客网 时间:2024/05/22 14:48

JDBC:

java DataBase Connecitvity

java数据库连接

JDBC可以做的三件事:

与数据库建立连接

发送操作数据库的语句

处理结果

java连接数据库的一般步骤

1、加载数据库连接驱动:

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

2、创建数据库连接的url,并获取数据库用户名和密码

String url = "jdbc:mysql://localhost:3306/ooo";String username = "root";String password = "123456"; 

3、创建数据库的连接

conn = DriverManager.getConnection(url, username, password);

将第二步中获取到的url、username、password作为参数,创建数据库的连接。

4、创建Statement对象:用于将sql语句发送到数据库

stmt = conn.createStatement();

5、执行sql语句

stmt.executeUpdate("delete from student where name = '李四'");rs = stmt.executeQuery("select * from student");

executeQuery(sql)语句用于执行查询语句,并将返回的结果,赋给ResultSet对象rs的结果集中,并用rs.next()方法循环处理返回的每一条记录。默认设为rs.next()指向第0条记录。
executeUpdate(sql)一般用于处理插入、修改、删除等操作。可以不讲执行的结果赋给ResultSet集合。

6、处理结果

7、关闭数据库的连接

最后打开的最先关闭。

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

代码示例:

import java.sql.DriverManager;import java.sql.*;public class TestJDBC {    public static void main(String[] args)  {        Connection conn = null;        Statement stmt = null;        ResultSet rs = null;        //提供驱动        String Driver = "com.mysql.jdbc.Driver";        //提供JDBC连接的URL   数据库,ip地址,端口号,数据库名        String url = "jdbc:mysql://localhost:3306/ooo";        String username = "root";        String password = "123456";        try{            //加载JDBC驱动程序            Class.forName(Driver);            //创建数据库的连接            conn = DriverManager.getConnection(url, username, password);            //创建statement对象,用于将sql语句发送到数据库                     stmt = conn.createStatement();//创建statement对象            //执行sql语句            stmt.executeUpdate("delete from student where name = '李四'");            rs = stmt.executeQuery("select * from student");            //处理结果            while(rs.next()){                System.out.print("学号:" + rs.getInt("id") +"  ");//自动装箱                System.out.print("姓名:" + rs.getString("name") +"     ");                System.out.print("性别:" + rs.getString("sex") +"     ");                System.out.print("出生日期:" + rs.getDate("birth") +"  ");                System.out.print("院系:" + rs.getString("department") +"   ");                System.out.print("地址:" + rs.getString("address"));                System.out.println();            }        }catch(ClassNotFoundException e){            e.printStackTrace();        }catch(SQLException e){            e.printStackTrace();        }finally{            try{                if(rs != null){                    rs.close();                }                if(stmt != null){                    stmt.close();                }                if(conn != null){                    conn.close();                }            }catch(SQLException e){                e.printStackTrace();            }        }    }}

执行结果:

这里写图片描述


连接数据库的封装①(仅仅使用配置文件)

将数据库的连接和关闭操作封装起来,类连接数据库时,直接调用即可。

1、新建配置文件,将连接数据库的驱动,url等信息放在配置文件中。

这里写图片描述

注意:创建的文件后缀名:.properties

2、创建类,存放数据库连接和关闭的方法

创建一个静态方法,获取配置文件中连接数据库需要的value值:

这里写图片描述

创建数据库的连接(静态方法):返回值类型为Connection

关闭数据库的连接(静态方法),传递三个参数(对象):最后打开的对象最先关闭

代码如下:

import java.io.IOException;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 driver;    private static String url;    private static String username;    private static String password;    static {        try{            Properties p = new Properties();            //加载配置文件        p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));            driver = p.getProperty("driver");            url = p.getProperty("url");            username = p.getProperty("username");            password = p.getProperty("password");            Class.forName(driver);        }catch(IOException e){            e.printStackTrace();        }catch(ClassNotFoundException e){            e.printStackTrace();        }    }    public static Connection createConnection(){        Connection conn = null;        try{            conn = DriverManager.getConnection(url, username, password);        }catch(SQLException e){            e.printStackTrace();        }        return conn;    }    public static void close(Connection conn, Statement stmt, ResultSet rs){        try{            if(rs!=null){                rs.close();            }            if(stmt!=null){                stmt.close();            }            if(conn!=null){                conn.close();            }        }catch(SQLException e){            e.printStackTrace();        }    }}

3、创建加载主类:

用于创建数据库的对象,创建对象时,直接调用第二步创建的完成连接的类的getConnection()方法;
创建Statement对象,将sql语句发送到数据库;
剩下的步骤跟连接数据库步骤一样。
关闭时,直接调用完成连接类的关闭数据库的静态方法。
主类代码如下:

import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class Test {    public static void main(String[] args) {        Connection conn = null;        Statement stmt = null;        ResultSet rs = null;        conn = JdbcUtil.createConnection();        try{            stmt = conn.createStatement();            rs = stmt.executeQuery("select * from student");            while(rs.next()){                System.out.print(rs.getString("name") + " ");                System.out.print(rs.getInt("id") + " ");                System.out.print(rs.getString("sex") + " ");                System.out.println();            }        }catch(SQLException e){            e.printStackTrace();        }finally{            JdbcUtil.close(conn, stmt, rs);        }    }}

运行结果:
这里写图片描述


连接数据库的封装②(连接池)

将多个连接放在一个连接池中,使用时直接从池中取。

连接池就是在封装的基础上,一次创建多个数据库的连接,放置在连接池中,使用时,直接从链接池中获取连接,使用完,再将连接放回连接池即可。

创建连接池的步骤:

1、创建List对象,将Connection对象放入List中,反复使用;

//创建连接池对象private static List<Connection> pool;

2、自定义连接池可以存放的最大值和最小值:

最小值:连接池首先创建最小值个连接,如果这些连接都被占用,而这时恰好有人要使用连接,可新建连接。
最大值:若连接池中的连接数达到最大值,若此刻还有人使用,不会再创建连接,而是需要等待。

//最大连接数private static final int POOL_MAX_SIZE = 100; //最小连接数private static final int POOL_MIN_SIZE = 10;

3、连接池的初始化

事先放入多个连接对象,一般首先创建的个数为连接池的最小值。

//初始化连接池,让池中的连接数达到最小值public void initPool(){    if(pool == null){        pool = new ArrayList<Connection>();    }    while(pool.size()<POOL_MIN_SIZE){        pool.add(JdbcUtil.createConnection());        System.out.println("初始化,连接池数为:"pool.size());        currentSize ++;        System.out.println(currentSize);    }}   

4、从连接池中获取连接

如果池中有可用的连接,将池中最后一个返回,同时将该连接从池中remove,表示正在使用;如果池中无可用的连接,则创建一个新的连接。

//从池中取连接,返回连接池中的最后一个连接public synchronized Connection getConnection(){    //Connection conn = null;    if(pool.size() > 0){        int last_index = pool.size()-1;        Connection conn = pool.get(last_index);        pool.remove(last_index);        return conn;    }else if(pool.size() == 0 && currentSize < 100){        pool.add(JdbcUtil.createConnection());        currentSize++;        System.out.println("当前连接池的个数为:" + currentSize);        Connection conn = pool.get(0);        pool.remove(0);        return conn;    }    throw new RuntimeException("连接数达到上限,请等待");}

5、关闭连接:不是真正的关闭,而是将用完的连接放回去。

示例代码:

import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.zkrtong.JdbcUtil;public class DBConnpool {    //创建连接池对象    private static List<Connection> pool;    //最大连接数    private static final int POOL_MAX_SIZE = 100;     //最小连接数    private static final int POOL_MIN_SIZE = 10;    int currentSize = 0;    public DBConnpool(){        initPool();    }    //初始化连接池,让池中的连接数达到最小值    public void initPool(){        if(pool == null){            pool = new ArrayList<Connection>();        }        while(pool.size()<POOL_MIN_SIZE){            pool.add(JdbcUtil.createConnection());            System.out.println("初始化,连接池数为:"+pool.size());            currentSize ++;            System.out.println(currentSize);        }    }       //从池中取连接,返回连接池中的最后一个连接    public synchronized Connection getConnection(){        //Connection conn = null;        if(pool.size() > 0){            int last_index = pool.size()-1;            Connection conn = pool.get(last_index);            pool.remove(last_index);            return conn;        }else if(pool.size() == 0 && currentSize < 100){            pool.add(JdbcUtil.createConnection());            currentSize++;            System.out.println("当前连接池的个数为:" + currentSize);            Connection conn = pool.get(0);            pool.remove(0);            return conn;        }        throw new RuntimeException("连接数达到上限,请等待");    }    //将连接放回池中    public synchronized void close(Connection conn){        pool.add(conn);    }}

对于今天的学习,JDBC连接数据库,可以接受,但对于连接池这块,之前没有接触过,还没有完全掌握。希望在以后的学习中能理解的更透彻。

原创粉丝点击