详解Java使用sqlite 数据库如何生成db文件

时间:2021-09-30 15:26:54

Java 使用Sqllite 数据库如何生成db文件

           本文主要介绍Java 使用Sqllite 数据库如何生成db文件的实现实例,网上资料不是很多,自己上网搜资料看到的一个实例,希望可以帮助到读者

实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import javax.sql.DataSource;
 
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
 
public class Main {
 
  public static void update(String sql) {
    DataSource data = getDataSource();
    Connection conn = null;
    try {
      conn = data.getConnection();
      PreparedStatement ps = conn.prepareStatement(sql);
      ps.executeUpdate();
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage());
    } finally {
      try {
        DataSourceUtils.doCloseConnection(conn, dataSource);
      } catch (Exception e) {
      }
    }
  }
 
  protected static BasicDataSource dataSource = null;
 
  public static DataSource getDataSource() {
    synchronized (Thread.class) {
      if (null == dataSource) {
        dataSource = new BasicDataSource();
        dataSource.setUrl("jdbc:sqlite:hp.db");
        dataSource.setDriverClassName("org.sqlite.JDBC");
      }
    }
    return dataSource;
  }
 
  public static void main(String[] args) throws Exception {
    update("drop table if exists COMPANY");
    update("CREATE TABLE COMPANY (ID INT,cname VARCHAR(40))");
 
    for (int x = 0; x < 300; x++) {
      update("insert into COMPANY(id , cname) values(" + x + " ,'xx" + x + "')");
    }
 
    PreparedStatement ps = getDataSource().getConnection().prepareStatement("select * from COMPANY");
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
      System.out.println(rs.getString("id") + "--" + rs.getString("cname"));
    }
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://hpgary.iteye.com/blog/2383347