进来准备使用一种embedded database,即嵌入式数据库,方便随项目本地存储。目前学习打算是sqlite和H2。
document:http://www.runoob.com/sqlite/sqlite-java.html
1.连接数据库
添加依赖jdbc:
org.xerial sqlite-jdbc 3.8.11.2
链接代码:
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 }