使用IDEA的Maven构建项目实现JDBC

1、在pom.xml文件中添加MySQL依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.kuang</groupId>
    <artifactId>javaweb-jdbc</artifactId>
    <version>1.0.0</version>

        <!--MySQL的驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
    </dependencies>


</project>

 

2、测试代码

package com.kuang.test;

import java.sql.*;

public class TestJdbc {
    public static void main(String[] args) throws Exception {
        //配置信息
        //useUnicode=true&characterEncoding=utf-8 解决中文乱码的问题
        String url = "jdbc:mysql://localhost:3306/jdbc_test01?useUnicode=true&characterEncoding=utf-8";
        String username = "root";
        String password = "123456";

        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");

        //2.连接数据库, 代表数据库
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.创建向数据库发送SQL的对象Statement, PreparedStatement : CRUD
        //PreparedStatement --- connection.prepareStatement(sql);
        Statement statement = connection.createStatement();


        //4.编写SQL
        String sql = "select * from users";
        //String sql = "delete from users where id=2";

        //受影响的行数, 增删改都是用executeUpdate()即可
        //int count = statement.executeUpdate(sql);

        //5.执行SQL, 返回一个ResultSet :结果集
        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()){
            System.out.println("id=" + rs.getObject("id"));
            System.out.println("name=" + rs.getObject("name"));
            System.out.println("password=" + rs.getObject("password"));
            System.out.println("email=" + rs.getObject("email"));
            System.out.println("birthday=" + rs.getObject("birthday"));
            System.out.println("======================================");
        }

        //6.关闭连接, 释放资源(一定要做) 先开后关
        rs.close();
        statement.close();
        connection.close();

    }
}

 

使用IDEA的Maven构建项目实现JDBC

上一篇:服务质量 0,1,2 - MQTT 核心系列:第六章


下一篇:jmeter:badboy录制