以下是Java连接数据库的示例代码,其中使用了MySQL数据库和JDBC驱动:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection(url, user, password);
// 创建Statement对象
stmt = conn.createStatement();
// 插入数据
String sql = "INSERT INTO student(name, number) VALUES('张三', '001'), ('李四', '002')";
stmt.executeUpdate(sql);
// 查询数据
sql = "SELECT * FROM student";
rs = stmt.executeQuery(sql);
// 打印结果
while (rs.next()) {
String name = rs.getString("name");
String number = rs.getString("number");
System.out.println("name: " + name + ", number: " + number);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,首先定义了连接数据库所需的URL、用户名和密码,然后使用`DriverManager.getConnection()`方法连接数据库。接着创建`Statement`对象,使用`executeUpdate()`方法插入数据,使用`executeQuery()`方法查询数据,并使用`ResultSet`对象遍历查询结果。最后在`finally`块中关闭资源。
本网转载内容版权归原作者和授权发表网站所有,仅供学习交流之用,如有涉及版权问题,请通知我们尽快处理。