准备
java 使用sqlite 需要安装SQLite JDBC Driver驱动
使用mavan项目可以直接构建需要的库,添加以下依赖。
添加依赖
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.30.1</version>
</dependency>
创建表
import java.sql.*;
public class SqliteTest {
public static void main(String[] args) {
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
Statement statement = connection.createStatement();
statement.execute("CREATE TABLE IF NOT EXISTS person(id integer primary key,name varchar not null,age integer )");
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据表的增删改查
添加数据
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
PreparedStatement statement = connection.prepareStatement("INSERT INTO person(NAME, AGE) VALUES (?,?);");
statement.setString(1,"Joe");
statement.setInt(2,18);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
删除数据
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
PreparedStatement statement = connection.prepareStatement("DELETE FROM person WHERE id=?");
statement.setInt(1,1);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
查找数据
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM person");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString(2)); // 注意:这里列的序号从1开始
System.out.println(resultSet.getInt(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
更新数据
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db")) {
PreparedStatement statement = connection.prepareStatement("UPDATE person SET age=?;");
statement.setInt(1,22);
int success = statement.executeUpdate();
System.out.println("成功更新了"+String.valueOf(success)+"条");
} catch (SQLException e) {
e.printStackTrace();
}
网友评论