· 9 years ago · Dec 01, 2016, 08:32 AM
1/**
2 *
3 * @author habib
4 */
5public class CustomSQLExceptionMessage {
6
7 static org.sqlite.SQLiteDataSource dataSource;
8
9 public static void main(String[] args) {
10 dataSource = new org.sqlite.SQLiteDataSource();
11 dataSource.setUrl("jdbc:sqlite:data.db3");
12 createTable();
13 select();
14 insert();
15 }
16
17 private static java.sql.Connection connection() throws java.sql.SQLException {
18 return dataSource.getConnection();
19 }
20
21 private static void createTable() {
22 System.out.println("Membuat tabel my_table...");
23 String QUERY_CREATE = "CREATE TABLE IF NOT EXISTS my_table (id INTEGER NOT NULL, name TEXT, PRIMARY KEY(id))";
24 try (java.sql.Statement execute = connection().createStatement();) {
25 execute.executeUpdate(QUERY_CREATE);
26 System.out.println("Table berhasil di buat!");
27 } catch (java.sql.SQLException ex) {
28 sqlErrorMessage(ex.getErrorCode());
29 }
30 }
31
32 private static void select() {
33 String QUERY_SELECT = "SELECT * FROM my_table";
34 try (java.sql.PreparedStatement preparedStatement = connection().prepareStatement(QUERY_SELECT)) {
35 java.sql.ResultSet result = preparedStatement.executeQuery();
36 do {
37 System.out.println("my_table[ID : " + result.getInt(1) + "] [ Nama : " + result.getString(2) + "]");
38 } while (result.next());
39 } catch (java.sql.SQLException ex) {
40 sqlErrorMessage(ex.getErrorCode());
41 }
42 }
43
44 private static void insert() {
45 String QUERY_INSERT = "INSERT INTO my_table VALUES(?,?)";
46 try (java.sql.PreparedStatement preparedStatement = connection().prepareStatement(QUERY_INSERT)) {
47 preparedStatement.setInt(1, 1);
48 preparedStatement.setString(2, "Java Programming");
49 preparedStatement.executeUpdate();
50 System.out.println("Data tersimpan!");
51 } catch (java.sql.SQLException ex) {
52 sqlErrorMessage(ex.getErrorCode());
53 //System.err.println("Kode : " + ex.getErrorCode() + " - Pesan : " + ex.getMessage());
54 }
55 }
56
57 private static void sqlErrorMessage(int code) {
58 switch (code) {
59 case 19:
60 System.err.println("Kolom mengandung Unik Key yang tidak boleh sama!");
61 break;
62 case 1:
63 System.err.println("SQL Error kolom tidak sesuai!");
64 break;
65 default:
66 //dan kode error lainnya
67 break;
68 }
69 }
70
71}