JDBC连接数据库的三种方式

JDBC程序的一般编写步骤

1、导入数据库驱动包
2、加载驱动
3、获取连接
4、执行SQL命令
5、处理数据
6、关闭资源

JDBC连接数据库方式一

public class ConnectionTest01 {
    public static void main(String[] args) throws Exception {
       Driver driver = new com.mysql.jdbc.Driver();
       Properties prop = new Properties();
       prop.setProperties("user","root");
       prop.setProperties("password","root");
       Connection conn = driver.connect("jdbc:mysql://localhost:3306/DatabaseName",prop);
       System.out.println(conn);
    }
}

JDBC连接数据库方式二

public class ConnectionTest02 {
    public static void main(String[] args) throws Exception {
       Class.forName("com.mysql.jdbc.Driver");
       Connection conn = DriverManagment.getConnection("jdbc:mysql://localhost:3306/DatabaseName","root","root");
       System.out.println(conn);
    }
}

JDBC连接数据库方式三

使用配置文件(properties属性文件)的方式

public class ConnectionTest03 {
    public static void main(String[] args) throws Exception {
        //创建配置文件,将文件创建在src下
        //读取属性文件
        InputStream is = Connection.class.getClassLoader().getResourceAsStream("name.properties");
        Properties prop = new Properties();
        prop.load(is);
        Class.forName(prop.getProperties("driver"));
        String url = prop.getProperties("url");
        String user = prop.getProperties("user");
        String password = prop.getProperties("password");
        Connection conn = DriverManagment.getConnection(url,user,password);
        System.out.println(conn);
    }
}

properties配置文件
注:在模块下面的src目录下创建name.properties文件
注:使用键值对存储数据,= 号两边不要有空格

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/DatabaseName
user=root
password=root

DatabaseName是数据库名字
第一个root是用户名
第二个root是密码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值