java 操作文件数据库的简单例子
import java.sql.Connection; import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class sqlite {
public static void main(String[] args) {
// 加载驱动
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("数据库驱动未找到!");
}
// 得到连接 会在你所填写的目录建一个你命名的文件数据库
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:sqlite:D:/test1.db", null,
null);
// 设置自动提交为false
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
// 判断表是否存在
ResultSet rsTables = conn.getMetaData().getTables(null, null,
"company", null);
if (rsTables.next()) {
System.out.println("已表存在");
} else {
stmt.executeUpdate("create table company (id,name);");
}
stmt.executeUpdate("insert into company values (1,'lideya');");
stmt.executeUpdate("insert into company values (2,'zahngdefa');");
stmt.executeUpdate("insert into company values (3,'minhantao');");
stmt.executeUpdate("insert into company values (6,'liudeya');");
stmt.executeUpdate("insert into company values (7,'zhangdefa');");
stmt.executeUpdate("insert into company values (8,'haohantao');");
// 提交
conn.commit();
// 得到结果集
ResultSet rs = stmt.executeQuery("select * from company;");
while (rs.next()) {
System.out.println("id = " + rs.getString("id"));
System.out.println("name = " + rs.getString("name"));
}
rs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQL异常!");
}
}
}