jdbc基础

1.什么是jdbc?
使用java代码(程序)发送sql语句的技术,就是jdbc技术!!!!
2.使用jdbc发送sql前提
登录数据库服务器(连接数据库服务器)
数据库的IP地址
端口
数据库用户名
密码

/**
 * jdbc连接数据库
 * @author APPle
 *
 */
public class Demo1 {
    //连接数据库的URL
    private String url = "jdbc:mysql://localhost:3306/day17";
                        // jdbc协议:数据库子协议:主机:端口/连接的数据库   //

    private String user = "root";//用户名
    private String password = "root";//密码

    /**
     * 第一种方法
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        //1.创建驱动程序类对象
        Driver driver = new com.mysql.jdbc.Driver(); //新版本
        //Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本

        //设置用户名和密码
        Properties props = new Properties();
        props.setProperty("user", user);
        props.setProperty("password", password);

        //2.连接数据库,返回连接对象
        Connection conn = driver.connect(url, props);

        System.out.println(conn);
    }

    /**
     * 使用驱动管理器类连接数据库(注册了两次,没必要)
     * @throws Exception
     */
    @Test
    public void test2() throws Exception{
        Driver driver = new com.mysql.jdbc.Driver();
        //Driver driver2 = new com.oracle.jdbc.Driver();
        //1.注册驱动程序(可以注册多个驱动程序)
        DriverManager.registerDriver(driver);
        //DriverManager.registerDriver(driver2);

        //2.连接到具体的数据库
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);

    }

    /**
     * (推荐使用这种方式连接数据库)
     * 推荐使用加载驱动程序类  来 注册驱动程序 
     * @throws Exception
     */
    @Test
    public void test3() throws Exception{
        //Driver driver = new com.mysql.jdbc.Driver();

        //通过得到字节码对象的方式加载静态代码块,从而注册驱动程序
        Class.forName("com.mysql.jdbc.Driver");

        //Driver driver2 = new com.oracle.jdbc.Driver();
        //1.注册驱动程序(可以注册多个驱动程序)
        //DriverManager.registerDriver(driver);
        //DriverManager.registerDriver(driver2);

        //2.连接到具体的数据库
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值