How to insert data (cadastre) in SQLite?

-2

Hello, my connection to SQLite is as follows:

Connection connection = null;

        try
          {
             // create a database connection
             connection = DriverManager.getConnection("jdbc:sqlite:database.db");

             Statement statement = connection.createStatement();
             statement.setQueryTimeout(30);  // set timeout to 30 sec.

             statement.executeUpdate("CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, address STRING, telephone STRING, celphone STRING, email STRING, cpf STRING, password STRING)");   


          }
        catch(SQLException e){  System.err.println(e.getMessage()); }     

    }

Is this connection correct? I would also like to know how to insert data into SQLite. I need to enter data in SQLite to make registrations in the program. The program is for Desktop and not for Android. I'm using Eclipse.

Thank you.

    
asked by anonymous 30.05.2018 / 05:36

1 answer

1

As you are using JDBC with does not change much regarding other banks only a few connection parameters.

Connection example with SQLite:

private Connection connect() {
    // SQLite connection string
    String url = "jdbc:sqlite:C://sqlite/db/test.db";
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(url);
    } catch (SQLException e) {
        System.out.println(e.getMessage());
    }
    return conn;
}

After connected, just follow the same steps as JDBC to make an insertion, Example:

public void insert(String column1, double column2) {
        String sql = "INSERT INTO teste(column1,column2) VALUES(?,?)";

        try (Connection conn = this.connect();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, column1);
            pstmt.setString(2, column2);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
    
30.05.2018 / 14:57