【尚硅谷19集】spring配置数据库mysql理解

老师用的德鲁伊的数据库,而我想用mysql的

pom导入代码

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

 连接池配置

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis_db?serverTimezone=Asia/Shanghai"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
</bean>

 测试

  public void jdbc() throws SQLException {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans02/beans3.xml");
        DataSource dataSource = context.getBean("dataSource", DataSource.class);
        Connection con = dataSource.getConnection();//建立数据库连接,获得连接对象con
        String sql = "select * from user";//查询语句
        PreparedStatement par = con.prepareStatement(sql);//通过PreparedStatement
        ResultSet resultSet = par.executeQuery();//执行查询语句,将数据写入到ResultSet中


        while (resultSet.next()){
            ArrayList arrayList = new ArrayList();
            int uid = resultSet.getInt(1);
           String uname = resultSet.getString(2);
            String address = resultSet.getString(3);
            arrayList.add(uid);
            arrayList.add(uname);
            arrayList.add(address);
            System.out.println(arrayList);
        }


    }

猜你喜欢

转载自blog.csdn.net/zhenghaochang/article/details/128702286