標籤:
進來準備使用一種embedded database,即嵌入式資料庫,方便隨項目本機存放區。目前學習打算是sqlite和H2。
document:http://www.runoob.com/sqlite/sqlite-java.html
1.串連資料庫
添加依賴jdbc:
<dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.8.11.2</version></dependency>
連結代碼:
package com.test.database.sqlite;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;/** * Created by miaorf on 2016/6/20. */public class SQLiteJDBC { public static void main(String[] args) { Connection c = null; try { Class.forName("org.sqlite.JDBC"); c= DriverManager.getConnection("jdbc:sqlite:test.db"); } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); } System.out.println("Open databse successfully"); }}
執行結束髮現,在項目根目錄會產生一個叫做test.db的檔案,這就是我們的資料庫了。
2. 建立表
1 package com.test.database.sqlite; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.SQLException; 6 import java.sql.Statement; 7 8 /** 9 * Created by miaorf on 2016/6/20.10 */11 public class SQLiteJDBC {12 13 public static void main(String[] args) {14 15 Connection c = null;16 Statement stmt = null;17 try {18 Class.forName("org.sqlite.JDBC");19 c= DriverManager.getConnection("jdbc:sqlite:test.db");20 System.out.println("Opened database successfully");21 22 stmt = c.createStatement();23 String sql = "CREATE TABLE COMPANY " +24 "(ID INT PRIMARY KEY NOT NULL," +25 " NAME TEXT NOT NULL, " +26 " AGE INT NOT NULL, " +27 " ADDRESS CHAR(50), " +28 " SALARY REAL)";29 stmt.executeUpdate(sql);30 stmt.close();31 c.close();32 33 System.out.println("create table successfully");34 35 } catch (ClassNotFoundException e) {36 e.printStackTrace();37 }catch (SQLException e) {38 e.printStackTrace();39 }40 41 42 }43 44 45 }
sqlite - java 初學