Java连接数据库、Properties连接数据库、SpringBoot连接数据库

普通Web项目Java连接数据库

一、使用配置文件方式连接

该方法好处在于方便程序员随时修改数据库的账号和密码,而不用在意误修改代码而发生变化,维护简单

新建文件db.properties配置文件
文件中写入如下信息(此文件我们称之为连接池)

url=jdbc:mysql://localhost:3306/party?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
user=root
password=123456

xml配置文件

<!--数据库连接池依赖-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

Properties配置文件连接数据库

//利用连接池来连接数据库,并且使用了配置文件,方便读取和修改
public class ConnectionFactory {

    //先声明连接池对象
     static DruidDataSource source = null;
     
     //静态加载一下连接
     static{
        try {
            //使用配置文件
            Properties properties = new Properties();
            //我们上面写好的连接池的位置
            properties.load(new FileReader(
                    "src/main/resources/db.properties"));
            source = new DruidDataSource();
            source.setUrl(properties.getProperty("url"));
            source.setUsername(properties.getProperty("user"));
            source.setPassword(properties.getProperty("password"));
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
         return getConnection(true);
    }


    public static Connection getConnection(boolean autoCommit){
        Connection connection = null;
         try {
             connection = source.getConnection();
            //自动模式,执行所有的 SQL 语句,并作为单个事务被自动提交
            connection.setAutoCommit(autoCommit);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
         return connection;
    }
}

二、不使用配置文件方式连接

该方法好处就是简单,适用于初学者

public class ConnectionFactory {

	//加载驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

     //静态加载一下连接
     static{
        try {
            String url = "jdbc:mysql://localhost:3306/party?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false";
            String userName = "root";
            String password = "123456";
            connection = DriverManager.getConnection(url, userName, password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
         return getConnection(true);
    }


    public static Connection getConnection(boolean autoCommit){
        Connection connection = null;
         try {
             connection = source.getConnection();
            //自动模式,执行所有的 SQL 语句,并作为单个事务被自动提交
            connection.setAutoCommit(autoCommit);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
        }
         return connection;
    }
}

三、数据库的简单增删改查

3.0 测试连接

    //测试连接
    public static void main(String[] args) {
    	//获取连接对象
        Connection connection = ConnectionFactory.getConn();
        System.out.println(connection);
    }

如果可以输出,则表示连接成功

3.1 概述

execute:返回boolean类型的值,代表是否有结果集返回(如果执行select操作,是有ResultSet的,返回值为true)

executeUpdate:返回int类型的值,代表的是操作执行完成后受影响的数据库的行计数

executeQuery:返回的是ResultSet,返回的是查询到的对象集合

3.2 执行语句

PreparedStatement ps = connection.prepareStatement(sql);;

  1. 创建时就需要传递sql语句,执行的时候不需要传递sql语句

  2. 如果涉及到动态参数的传递,可以使用字符串拼接,也可以使用?占位的形式给?号传值

  3. 使用的是pstmt.setType(index,value)index从1开始

  4. 提供预编译的功能,某种程度上可以避免sql注入的问题

3.3 简单实例

//新建表
public void createTable() throws SQLException {
	//利用我们3.1或者3.2的方法获得数据库连接对象
    Connection connection = ConnectionFactory.getConnection();
    //写完sql语句之后再换行
    String sql1 = "create table hus(" +
        "id int primary key," +
        "name varchar(20)," +
        "salary double)";
    PreparedStatement ps1 = connection.prepareStatement(sql1);
    ps1.execute();
}


//插入数据
public void insertIntoOneToOneTable() throws SQLException {
    Connection connection = ConnectionFactory.getConnection();
    String sql = "insert into hus values (?,?,?)";
    PreparedStatement ps = connection.prepareStatement(sql);
    //第一个参数是指定下标(并且set的时候要注意参数类型),第二个参数是指定插入的内容
    ps.setInt(1,2);
    ps.setString(2,"tom");
    ps.setInt(3,2000);
    ps.execute();
    System.out.println("插入数据成功!");
}


//查询
public void query() throws SQLException {
    Connection connection = ConnectionFactory.getConnection();
    String sql = "select * from wife";
    PreparedStatement ps = connection.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while (rs.next()){
        int id = rs.getInt(1);
        String name = rs.getString(2);
        int hus_id = rs.getInt(3);
        System.out.println(id+"--"+name+"--"+hus_id);
    }
}

SpringBoot连接数据库

框架连接数据库就简单多了

  • 勾选相应的依赖 JDBC APIMySQL Driver
    在这里插入图片描述
  • 然后即可构建项目,删除application.properties,新建application.yaml文件
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver

即可连接成功

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值