Java操作SQL数据库(JDBC)

时间:2021-07-01 16:28:37   收藏:0   阅读:0

0.引入驱动jar包

使用jdbc进行具体操作前,需要引入相关数据库的jar包, 或者使用mave管理依赖

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.34.0</version>
</dependency>

1.加载驱动

Class.forName(DRIVER);

2.获取数据库连接对象

Connection conn=DriverManager.getConnection(URL);

3.创建(预处理)语句对象

普通语句对象

Statement stmt=conn.createStatement();

预处理语句对象

PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setXxx(int parameterIndex, Xxx x); // 参数索引从1开始

4.执行sql语句

普通语句对象执行sql

boolean b=stmt.execute(sql);
int i=stmt.executeUpdate(sql);
ResultSet resultSet=stmt.executeQuery(sql);

预处理语句对象执行sql

int i=pstmt.executeUpdate();
ResultSet resultSet=pstmt.executeQuery();

5.处理结果集

while(resultSet.next())
{
    int id=resultSet.getInt("id");
    String name=resultSet.getString("name");
}

6.关闭结果集,语句,连接

resultSet.close();
stmt.close();
conn.close();

jdbc工具类封装

在类路径下创建配置文件

mysql.properties

DRIVER=com.mysql.cj.jdbc.Driver
URL=jdbc:mysql://localhost:3306/test
USER=root
PASSWORD=root

DBUtil.java

public class DBUtil
{
    private static final String URL;
    private static final String USER;
    private static final String PASSWORD;

    private DBUtil(){}

    static
    {
        // 从properties文件中加载配置信息
        ResourceBundle bundle=ResourceBundle.getBundle("mysql");
        String DRIVER=bundle.getString("DRIVER");
        URL=bundle.getString("URL");
        USER=bundle.getString("USER");
        PASSWORD=bundle.getString("PASSWORD");

        try
        {
            Class.forName(DRIVER);
        }
        catch(ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException
    {
        return DriverManager.getConnection(URL,USER,PASSWORD);
    }
}
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!