JDBC java数据连接 读取properties 数据库连接池 预编译

Posted hello4world

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC java数据连接 读取properties 数据库连接池 预编译相关的知识,希望对你有一定的参考价值。

1.创建连接,下载mysql驱动(JDBC接口的实现类,就是一个jar包) 

public class Demo01 {
    public static void main(String[] args)
            throws ClassNotFoundException, SQLException {
        //1. 注册驱动  告诉虚拟机使用的是哪个数据库软件
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获取连接对象
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
        System.out.println(conn);
        //3. 创建SQL执行对象
        Statement stat = conn.createStatement();
        //4. 执行SQL语句
        String sql = "create table jdbct1 (id int primary key,name varchar(10))";
        stat.execute(sql);
        System.out.println("执行完成!");
        //5. 关闭资源
        conn.close();    
    }
}
public class Demo02 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {    
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
        Statement stat = conn.createStatement();
        String sql = "drop table jdbct1";
        stat.execute(sql);
        System.out.println("执行完成");
        conn.close();    
    }
}
public class Demo03 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
        Statement stat = conn.createStatement();
        //执行增删改SQL
//        String sql = "insert into emp(empno,ename) values(100,‘Tom‘)";
//        String sql = "update emp set ename=‘Jerry‘ where empno=100";
//        String sql = "delete from emp where empno=100";
//        stat.executeUpdate(sql);
        //执行查询SQL
        String sql = "select ename,sal,job from emp";
        //查询到的结果装进了rs对象中
        ResultSet rs = stat.executeQuery(sql);
        //遍历结果集对象获取数据
        while(rs.next()) {
            //可以通过字段名和字段位置获取参数
            String name = rs.getString(1);
            double sal = rs.getDouble(2);
            String job = rs.getString(3);
            System.out.println(name+":"+sal+":"+job);
        }    
        System.out.println("执行成功!");
        conn.close();
    }
}

2.DBUtil,返回一个Connection对象

public class DBUtils {
    public static Connection getConn() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
        return conn;
    } 
}
public class Demo01 {
    public static void main(String[] args) {        
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            //创建SQL执行对象
            Statement stat = conn.createStatement();
            //执行SQL
            String sql = "select ename from emp";
            ResultSet rs = stat.executeQuery(sql);
            while(rs.next()) {
                String name = rs.getString("ename");
                System.out.println(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.读取properties文件

public class Demo02 {
    public static void main(String[] args) throws IOException {
        //创建读取配置文件数据的对象
        Properties p = new Properties();
        //获取文件流
        InputStream ips = Demo02.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //把文件加载到属性对象中
        p.load(ips);
        //读取数据
        String name = p.getProperty("name");
        String age = p.getProperty("age");
        System.out.println(name+":"+age);
    }
}

4.数据库连接池

public class Demo03 {
    public static void main(String[] args) throws SQLException {
        //创建数据库连接池对象
        BasicDataSource ds = new BasicDataSource();
        //设置数据库连接信息
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/newdb3");
        ds.setUsername("root");
        ds.setPassword("root");
        //设置初始连接数量
        ds.setInitialSize(3);
        //设置最大连接数量
        ds.setMaxActive(5);
        //从连接池中获取连接  抛异常
        Connection conn = ds.getConnection();
        System.out.println(conn);
    }
}

5.DBUtils,增强版本

public class DBUtils {
    private static BasicDataSource ds;
    static {
        Properties p = new Properties();
        InputStream ips = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            p.load(ips);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String driver = p.getProperty("driver");
        String url = p.getProperty("url");
        String username = p.getProperty("username");
        String password = p.getProperty("password");
        //创建数据库连接池对象
        ds = new BasicDataSource();
        //设置数据库连接信息
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        //设置初始连接数量
        ds.setInitialSize(3);
        //设置最大连接数量
        ds.setMaxActive(5); 
    }
    public static Connection getConn() throws Exception {
        //从连接池中获取连接  抛异常
        Connection conn = ds.getConnection();
        return conn;
    }
}

6.预编译

public class Demo04 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = s.nextLine();
        System.out.println("请输入密码");
        String password = s.nextLine();    
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            /*Statement stat = conn.createStatement();
            String sql = "select count(*) from user "
                    + "where username=‘"+username
                    +"‘ and password=‘"+password+"‘";
            //输出后在终端中测试
            System.out.println(sql);
            ResultSet rs = stat.executeQuery(sql);*/
            //通过预编译的SQL执行对象解决SQL注入问题
            String sql = "select count(*) from user where username=? and password=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            //把?替换成真正的变量
            ps.setString(1, username);
            ps.setString(2, password);
            //执行SQL语句
            ResultSet rs = ps.executeQuery();        
            while(rs.next()) {
                int count = rs.getInt(1);
                if(count>0) {
                    System.out.println("登录成功!");
                }else {
                    System.out.println("登录失败!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

7.批量操作

public class Demo05 {
    public static void main(String[] args) {
        String sql1 = "insert into emp(empno,ename) values(200,‘aaa‘)";
        String sql2 = "insert into emp(empno,ename) values(201,‘bbb‘)";
        String sql3 = "insert into emp(empno,ename) values(202,‘ccc‘)";
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            Statement stat = conn.createStatement();
            //添加到批量操作
            stat.addBatch(sql1);
            stat.addBatch(sql2);
            stat.addBatch(sql3);
            //执行批量操作
            stat.executeBatch();
            System.out.println("执行完成");
        } catch (Exception e) {
            e.printStackTrace();
        }        
    }
}
public class Demo06 {
    public static void main(String[] args) {
//create table person(name varchar(10),age int);
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            String sql = "insert into person values(?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            for (int i = 1; i <= 100; i++) {
                ps.setString(1, "name"+i);
                ps.setInt(2, 100+i);
                //添加到批量操作
                ps.addBatch();
                //避免内存溢出每隔30条执行一次
                if(i%30==0) {
                    ps.executeBatch();
                }
            }
            ps.executeBatch();//执行批量操作        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

8.返回自增主键

public class Demo08 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入员工姓名");
        String name = s.nextLine();
        System.out.println("请输入工资");
        int sal = s.nextInt();
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            String sql = "insert into myemp values (null,?,?)";
            //设置获取自增主键值
            PreparedStatement ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            //替换问号内容
            ps.setString(1, name);
            ps.setInt(2, sal);
            ps.executeUpdate();
            System.out.println("保存完成!");
            //开始获取自增主键值
            ResultSet rs = ps.getGeneratedKeys();
            while(rs.next()) {
                int id = rs.getInt(1);
                System.out.println("自增主键值:"+id);
            }    
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }
}

9.获取数据库本身信息

public class Demo10 {
    public static void main(String[] args) {
        //获取连接
        try (Connection conn = DBUtils.getConn();) {
            //获取数据库元数据对象
            DatabaseMetaData dbmd = conn.getMetaData();
            System.out.println("数据库名:"+dbmd.getDatabaseProductName());
            System.out.println("数据库驱动版本:"+dbmd.getDriverVersion());
            System.out.println("用户名:"+dbmd.getUserName());
            //获取和表相关的元数据
            String sql = "select * from emp";
            Statement stat = conn.createStatement();
            ResultSet rs = stat.executeQuery(sql);
            //获取元数据对象
            ResultSetMetaData rsmd = rs.getMetaData();
            //获取字段数量
            int count = rsmd.getColumnCount();
            //遍历字段名和类型
            for (int i = 0; i < count; i++) {
                String name = rsmd.getColumnName(i+1);
                String type = rsmd.getColumnTypeName(i+1);
                System.out.println(name+":"+type);
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上是关于JDBC java数据连接 读取properties 数据库连接池 预编译的主要内容,如果未能解决你的问题,请参考以下文章

Jdbc连接问题的properties文件配置

读取*.properties文件连接数据库

java jdbc连接数据库,Properties 属性设置参数方法

如何把数据库的properties文件内容读取到Java中

后端开发JDBC获取数据库连接的方式

后端开发JDBC获取数据库连接的方式