6、 简单叙述数据库调用的执行流程,并使用代码描述 1、数据库(test.db)创建过程; 2、Person表创建过程,字段包括:id(整型,自增,主键),name(64个字符),age(整型),gender(布尔型),height(浮点型); 3、插入一条记录并查询记录代码。
时间: 2024-03-26 16:35:32 浏览: 106
数据库调用的执行流程大致如下:
1. 加载数据库驱动程序。
2. 创建数据库连接。
3. 创建Statement对象或PreparedStatement对象。
4. 执行SQL语句。
5. 处理结果集。
6. 关闭结果集、Statement对象、数据库连接。
以下是SQLite数据库的创建和使用过程的代码示例:
1. 创建数据库(test.db):
```
import java.sql.*;
public class CreateDB {
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
String url = "jdbc:sqlite:test.db";
conn = DriverManager.getConnection(url);
System.out.println("创建数据库成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
2. 创建Person表:
```
import java.sql.*;
public class CreateTable {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
String url = "jdbc:sqlite:test.db";
conn = DriverManager.getConnection(url);
stmt = conn.createStatement();
String sql = "CREATE TABLE Person (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(64), age INTEGER, gender BOOLEAN, height REAL)";
stmt.executeUpdate(sql);
System.out.println("创建Person表成功!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
3. 插入一条记录并查询记录:
```
import java.sql.*;
public class InsertAndSelect {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
String url = "jdbc:sqlite:test.db";
conn = DriverManager.getConnection(url);
String sql = "INSERT INTO Person (name, age, gender, height) VALUES (?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Alice");
pstmt.setInt(2, 18);
pstmt.setBoolean(3, false);
pstmt.setDouble(4, 1.65);
pstmt.executeUpdate();
sql = "SELECT * FROM Person";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
boolean gender = rs.getBoolean("gender");
double height = rs.getDouble("height");
System.out.println(id + "\t" + name + "\t" + age + "\t" + gender + "\t" + height);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
阅读全文