java同一个数据库调用不同的值
时间: 2023-09-16 07:10:03 浏览: 32
如果你想在同一个Java程序中多次调用同一个数据库的不同数值,可以使用Java Database Connectivity (JDBC) API。下面是一个简单的例子,它使用JDBC API连接到MySQL数据库,并查询一个表中的不同值:
```
import java.sql.*;
public class Example {
public static void main(String[] args) {
try {
// Connect to database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "mypassword");
// Query the database
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// Process the results
while (rs.next()) {
String value = rs.getString("mycolumn");
System.out.println(value);
}
// Close the connection
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们连接到名为"mydatabase"的MySQL数据库,并查询一个名为"mytable"的表。我们使用ResultSet对象来处理查询结果,并使用getString()方法来提取每个行中"mycolumn"列的值。最后,我们关闭了ResultSet对象、Statement对象和Connection对象。