jdbc的Statement插入一条数据 给一个例子
时间: 2023-06-03 10:06:09 浏览: 70
好的,以下是一个使用 JDBC 的 Statement 插入一条数据的例子:
```java
import java.sql.*;
public class InsertDataExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动器
Class.forName(JDBC_DRIVER);
// 打开一个连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行插入数据的请求
System.out.println("创建语句...");
stmt = conn.createStatement();
String sql = "INSERT INTO customers " +
"VALUES (1001, '张三', '北京', '12345')";
stmt.executeUpdate(sql);
System.out.println("插入数据完成!");
// 关闭连接
stmt.close();
conn.close();
} catch(SQLException se) {
// 处理 JDBC 异常
se.printStackTrace();
} catch(Exception e) {
// 处理 Class.forName 异常
e.printStackTrace();
} finally {
// 关闭资源
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
```
请注意,这只是一个示例,并且需要根据实际情况修改数据库 URL、用户名、密码等信息。