1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;
import java.util.List; import java.util.ArrayList;
public class JdbcMain { public static void main(String[] args) throws ClassNotFoundException { Class.forName("org.sqlite.JDBC"); try(Connection connection = DriverManager.getConnection("jdbc:sqlite:contactmgr.db")) { Statement statement = connection.createStatement(); statement.executeUpdate("DROP TABLE IF EXISTS contacts"); statement.executeUpdate("CREATE TABLE contacts (id INTEGER PRIMARY KEY, firstname STRING, lastname STRING, email STRING, phone INT(10))"); statement.executeUpdate("INSERT INTO contacts (firstname, lastname, email, phone) VALUES('Liu', 'Lixiang', 'liulixiang1988@gmail.com', 1234567890)"); statement.executeUpdate("INSERT INTO contacts (firstname, lastname, email, phone) VALUES('Long', 'Long', 'abc@gmail.com', 0987654321)"); ResultSet rs = statement.executeQuery("SELECT * FROM contacts"); while(rs.next()){ int id = rs.getInt("id"); String firstName = rs.getString("firstname"); String lastName = rs.getString("lastname"); System.out.printf("%s %s (%d)", firstName, lastName, id); } } catch (SQLException ex) { System.err.printf("There was a database error: %s%n",ex.getMessage()); } } }
|