java JAVA - interagir avec une BDD

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java JAVA - interagir avec une BDD相关的知识,希望对你有一定的参考价值。

import java.util.ArrayList;
import java.util.List;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Hello world!
 *
 */
public class App 
{
    public static Connection connect(String databasePath) {
        Connection conn = null;

        try {
            String url = "jdbc:sqlite:test.sqlite";

            conn = DriverManager.getConnection(url);

        } catch (SQLException e) {
            e.printStackTrace();
        } 

        return conn;
    }

    public static void main( String[] args )
    {
        System.out.println("Trying insert.");
        if (insert("let's booboo"))
            System.out.println("Insert successfully executed.");
        else
            System.out.println("Insert could not be executed.");
        
        System.out.println("Trying select.");
        List<String> rows = select();
        if (rows != null){
            System.out.println("Rows:");
            for (String msg: rows){
                System.out.println(msg);
            }
        } else {
            System.out.println("No rows.");
        }
    }

    public static Boolean insert(String msg){
        String path = "test.sqlite";
        String query = "insert into post(msg) values(?)";

        boolean failed = false;

        try (Connection conn = connect(path);
             PreparedStatement pstmt = conn.prepareStatement(query)) {

            pstmt.setString(1, msg);
            pstmt.executeUpdate();

        } catch (SQLException e){
            e.printStackTrace();
            failed = true;
        } catch (NullPointerException e){
            System.err.println("Connection could not be opened, insert statement aborted.");
            failed = true;
        }

        return !failed;
    }

    public static List<String> select(){
        String path = "test.sqlite";
        String query = "select msg from post";

        List<String> rows = new ArrayList<String>();

        try (Connection conn = connect(path);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()){
                rows.add(rs.getString("msg"));
            }

        } catch (SQLException e){
            e.printStackTrace();
        } catch (NullPointerException e){
            System.err.println("Connection could not be opened, select statement aborted.");
        }

        return rows;
    }
}

以上是关于java JAVA - interagir avec une BDD的主要内容,如果未能解决你的问题,请参考以下文章

Java面试-- Java赋值表达式

Java16的新特性

java 数组操作实例

Java泛型Number能比较大小吗?

[Java] Java反射

第一个Java应用