Hoou
Hoou

Reputation: 31

JDBC SQLite Update

I'm new in jdbc sqlite. I would like to know how to execute an update. For example i have a table called people name, and occupation inside. Should i use PreparedStatement?

PreparedStatement change = conn.prepareStatement("Update people set name = ? ");
change.setString(1, "John");

ResultSet rs = stat.executeQuery("select * from people where name = 'Gandhi';");
while (rs.next()) {
    System.out.println("name = " + rs.getString("name"));
    System.out.println("job = " + rs.getString("occupation"));
}
rs.close();
conn.close();

I'd like to ask the proper way. Thanks you..

Upvotes: 3

Views: 8119

Answers (2)

therock
therock

Reputation: 21

You might want to check Java and SQLite

Example from the post:

package com.rungeek.sqlite;

import java.sql.Connection;
import java.sql.DriverManager; 
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test {
 public static void main(String[] args) throws Exception {
    Class.forName("org.sqlite.JDBC");
    Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
    Statement stat = conn.createStatement();
    stat.executeUpdate("drop table if exists people;");
    stat.executeUpdate("create table people (name, occupation);");
    PreparedStatement prep = conn.prepareStatement(
        "insert into people values (?, ?);");

    prep.setString(1, "Gandhi");
    prep.setString(2, "politics");
    prep.addBatch();
    prep.setString(1, "Turing");
    prep.setString(2, "computers");
    prep.addBatch();
    prep.setString(1, "Wittgenstein");
    prep.setString(2, "smartypants");
    prep.addBatch();

    conn.setAutoCommit(false);
    prep.executeBatch();
    conn.setAutoCommit(true);

    ResultSet rs = stat.executeQuery("select * from people;");
    while (rs.next()) {
        System.out.println("name = " + rs.getString("name"));
        System.out.println("job = " + rs.getString("occupation"));
    }
    rs.close();
    conn.close();
}
}

Thanks,

Upvotes: 2

user330315
user330315

Reputation:

You are not "executing" the update. You need to call change.executeUpdate() in order to send the UPDATE statement to the engine.

(And as ZeroPage has pointed out: remove the ; in the SQL string)

Upvotes: 2

Related Questions