JDBC连接数据库核心六步(ps:看的别人的)

package six_jdbc;

import java.sql.*;

public class Dbdemo {
    public static void main(String[] args) {
        ResultSet result = null;
        Connection con = null;
        Statement statement = null;

        try {
            //第一步:将想要连接的数据库驱动类加载到JVM中,加载过程中并向DriverManager注册Driver
            //成功加载后,会将Mysql的驱动Driver类的实例注册到DriverManager类中。???
            //使得线面我们获取Connection只需通过DriverManager就可以了。我不需要通过每个数据库具体的Driver.
            Class.forName("com.mysql.jdbc.Driver").newInstance();

            //第二步,通过DriverManager获取一个和mysql的连接实例
            String JDBCUrl = "jdbc:mysql://localhost:3306/kgw?useUnicode=true&characterEncodeing=utf-8";
            String username = "root";
            String password = "123456";
            //接受一个jdbcurl,username,password
            con = DriverManager.getConnection(JDBCUrl,username,password);

            //第三步通过con连接获取到Statement实例,执行sql语句
            statement = con.createStatement();//statement实例是用于一些不带参数的sql执行,查询,更新,插入
            //第四部步,statement执行sql语句,查询到的结果集到ResultSet实例,简单查询,唯有where语句的查询
            result = statement.executeQuery("select * from emp");
            //第五步:从结果集中获取数据
            while (result.next()){
                int id = result.getInt("id");
                int username1 = result.getInt("username");
                int pwd = result.getInt("pwd");
                System.out.println(id+ "\t" + username1 + "" + pwd);
            }

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //第六步释放资源
            //关闭JDBC对象 操作完成以后要把所有使用的JDBC对象全都关闭,
            // 以释放JDBC资源,关闭顺序和声 明顺序相反: 1、关闭记录集 2、关闭声明 3、关闭连接对象
            try {
                if(result != null){
                    result.close();
                }
                if(statement != null){
                    statement.close();
                }
                if(con != null){
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值