jdbc学习

如何使用jdbc

一、连接到数据库

1.导入驱动

导入驱动mysql-connector-java-5.1.47.jar,放在lib文件夹中,使用哪个数据库版本就要使用对应的驱动,使用命令行查询数据库版本

select version();

2.加载驱动

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

如果mysql版本大于8,使用下面这段加载驱动

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

3.连接数据库

Connection connection = DriverManager.getConnection(url, username, password);

url的格式一般为

== jdbc:mysql://localhost:3306/lession03?useUnicode=true&characterEncoding=utf8&useSSL=false==

4.获取执行sql语句的对象,statement

Statement statement = connection.createStatement();

5.获取结果集

statement相关方法

statement.executeQuery(sql);//执行查询,返回resultset结果
statement.execute();//执行sql语句,不建议使用
statement.executeUpdate();//执行更新语句,返回受影响的行数

ResultSet相关方法

resultSet.next();//移动到下一行数据

resultSet.getObject();//以对象返回该列的数据

resultSet.getString();//返回特定列的字符串

resultSet.geInt();//返回特定列的整数

ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {
    System.out.println("Sid="+resultSet.getObject("Sid"));
    System.out.println("Sname="+resultSet.getObject("Sname"));
    System.out.println("Sage="+resultSet.getObject("Sage"));
    System.out.println("Ssex="+resultSet.getObject("Ssex"));
    System.out.println("===============================");
}

6.关闭连接

resultSet.close();
statement.close();
connection.close();

数据库连接非常耗资源,使用完毕需要关闭,一般后开启的先关闭

二、封装jdbcutils

1.连接数据库只加载一次驱动,所以加载驱动放在静态代码块中

2.对外提供获取数据库连接和释放连接的方法

完整代码

public class JdbcUtil {

    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false";
    private static String username = "root";
    private static String password = "123456";

    static {

        try {
//            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
//            Properties properties = new Properties();
//            properties.load(in);
//
//            driver = properties.getProperty("driver");
//            url = properties.getProperty("url");
//            username = properties.getProperty("username");
//            password = properties.getProperty("password");

            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static void release(Connection conn,Statement st,ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (st!=null){
            try {
                st.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

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

三、使用properties文件连接到数据库

1.将连接到数据库的信息写在配置文件中 xx.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456

2.加载配置文件中的信息

配置文件需要放在源码文件夹下,才能使用类加载器的getResourceAsStream()方法读取到

InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);

driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");

四、使用PreparedStatement执行sql

1.使用statement执行sql语句存在数据库注入的风险

String sql = "insert into users (username,password,email,birth) values (?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);

ps.setString(1, "李四");
ps.setString(2, "123456");
ps.setString(3, "998989@qq.com");
ps.setDate(4, new Date(new java.util.Date().getTime()));

int i = ps.executeUpdate();

五、jdbc操作事务

1.关闭自动提交

2.执行sql

3.提交

4.失败回滚, jdbc中事务执行失败会自动回滚,可不用写回滚代码

try {
    conn = JdbcUtil.getConnection();

    conn.setAutoCommit(false);

    String sql1 ="update account set money = money-100 where name='A'";
    st = conn.prepareStatement(sql1);
    st.executeUpdate();

    String sql2 ="update account set money = money+100 where name='B'";
    st = conn.prepareStatement(sql2);
    st.executeUpdate();

    conn.commit();
    System.out.println("转账成功!");
} catch (SQLException throwables) {
    try {
        conn.rollback();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    throwables.printStackTrace();
}finally {
    JdbcUtil.release(conn,st,rs);
}

六、连接池技术

开源连接池的本质就是实现了datasource接口,调用datasource的getConnection()方法获取连接对象Connection

1.DBCP

  • 导入commons-dbcp-1.4.jar,commons-pool-1.6.jar
  • 导入配置文件dbcp.properties
########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
#用户名
username=root
#密码
password=123456
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties = new Properties();
properties.load(in);

ds = BasicDataSourceFactory.createDataSource(properties)

2.C3P0

  • 导入mchange-commons-java-0.2.20.jar,c3p0-0.9.5.5.jar,导入配置文件c3p0-config.xml(必须是这个文件名)
    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
       <!--默认配置-->
        <default-config>  
            <property name="initialPoolSize">10</property>  
            <property name="maxIdleTime">30</property>  
            <property name="maxPoolSize">100</property>  
            <property name="minPoolSize">10</property>  
            <property name="maxStatements">200</property>  
        </default-config>  
      
       <!--配置连接池mysql-->
        <named-config name="mysql">  
            <property name="driverClass">com.mysql.jdbc.Driver</property>  
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/CoupleSpace</property>  
            <property name="user">root</property>  
            <property name="password">root</property>  
            <property name="initialPoolSize">10</property>  
            <property name="maxIdleTime">30</property>  
            <property name="maxPoolSize">100</property>  
            <property name="minPoolSize">10</property>  
            <property name="maxStatements">200</property>  
        </named-config>  
        
        <!--配置连接池2-->
        ......
        <!--配置连接池3-->
        ......
        <!--配置连接池4-->
        ......
    </c3p0-config>
    

    加载配置文件,不指定配置名使用默认配置

    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    

3.Druid

七、dbutils

简化jdbc对数据库的操作

1.导入commons-dbutils-1.7.jar

2.关键类

(1) QueryRunner

QueryRunner(Datasource),创建queryrunner对象

query(sql,resultsethandler,obj…params)

update(sql,obj…params)

(2) 数据集处理类ResultSetHandler

ArrayHandler以数组形式返回第一行数据

ArrayListHandler集合数组返回所有数据

MapHandler以键值对返回第一行数据

MapListHandler将每一行数据放在map中以list返回所有行数据

BeanHandler以定义的类返回数据

BeanListHandler将每一行数据放到定义类中以list返回数据

ScalarHandler …

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值