java mysql+sqlite普通查询

发布时间 2023-03-24 16:04:53作者: laremehpe
import java.sql.*;

public class Test {
    public static void main(String[] args) {
        try {
//            new Test().queryMySql();
            new Test().querySqlite();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }


    private void querySqlite() throws ClassNotFoundException, SQLException {
        Connection c = null;
        Statement stmt = null;

        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:dictionary.db");
        c.setAutoCommit(false);
        stmt = c.createStatement();

        String en = "test";
        String sql = "SELECT * FROM dictionary WHERE en = \""+en+"\";";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            System.out.println(rs.getString("en"));
        }

        stmt.close();
        c.close();
    }
    private void queryMySql() throws SQLException {
        String URL = "jdbc:mysql://localhost/dictionary?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8";
        String USER = "username";
        String PASS = "********";
        Connection conn = DriverManager.getConnection(URL, USER, PASS);
        Statement stmt = conn.createStatement();
        String sql = "SELECT * FROM dictionary LIMIT 50;";
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            System.out.println(rs.getString("en"));
        }
        conn.close();
    }
}
<?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>org.example</groupId>
    <artifactId>QueryMissing</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.34.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
    </dependencies>
</project>