Java 操作sqllite 数据库,生成db文件

By - Last updated: 星期四, 七月 6, 2017
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"));
		}
	}
}

发表在 其他 • Tags: , , ↑Top 文章来源