jdbc连接SQLite操作

班思源
2023-12-01

项目导入sqlite-jdbc-3.7.2.jar

地址:http://pan.baidu.com/s/1kVHAGdD

 

示例:

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OpSqliteDBTest {
    
    private static final String Class_Name = "org.sqlite.JDBC";
    private static final String DB_URL = "jdbc:sqlite:E:\\workspace\\eclipse\\hello\\SQLiteTest\\src\\lib\\testdatabase.db";

    public static void main(String args[]) {
        Connection connection = null;
        try {
            connection = createConnection();
            func1(connection);
            System.out.println("Success!");
        }  catch (SQLException e) {
            System.err.println(e.getMessage());
        } catch(Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                // connection close failed.
                System.err.println(e);
            }
        }
    }
    
    // 创建Sqlite数据库连接
    public static Connection createConnection() throws SQLException, ClassNotFoundException {
        Class.forName(Class_Name);
        return DriverManager.getConnection(DB_URL);
    }

    public static void func1(Connection connection) throws SQLException {
        Statement statement = connection.createStatement();
        Statement statement1 = connection.createStatement();
        statement.setQueryTimeout(30); // set timeout to 30 sec.
        //statement1.executeUpdate(" CREATE TABLE user_name( id integer,  name text )  ");
        
        // 执行插入语句操作
        //statement1.executeUpdate("insert into user_name(id, name) values('1','2')");
        // 执行更新语句
        //statement1.executeUpdate("update user_name set name= '222' where id ='1'");
        
        // 执行查询语句
        ResultSet rs = statement.executeQuery("select * from user_name");
        while (rs.next()) {
            String col1 = rs.getString("id");
            String col2 = rs.getString("name");
            System.out.println("id = " + col1 + "  name = " + col2);
        }
    }
}

 

 

 

 类似资料: