进来准备使用一种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. 创建表
package com.test.database.sqlite; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement; /**
* Created by miaorf on 2016/6/20.
*/
public class SQLiteJDBC { public static void main(String[] args) { Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c= DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully"); stmt = c.createStatement();
String sql = "CREATE TABLE COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS CHAR(50), " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close(); System.out.println("create table successfully"); } catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
} } }