Java执行sql查询语句并返回值
时间: 2024-01-26 07:04:55 浏览: 27
可以使用Java中的JDBC来执行SQL查询语句并返回值。以下是一个示例代码:
```java
import java.sql.*;
public class SQLQueryExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; // JDBC驱动程序
static final String DB_URL = "jdbc:mysql://localhost:3306/exampledb"; // 数据库URL
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("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while(rs.next()){
// 通过列名获取值
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// 打印结果
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理JDBC错误
se.printStackTrace();
}catch(Exception e){
// 处理其他错误
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!");
}
}
```
在这个示例中,我们首先注册了MySQL的JDBC驱动程序。然后,我们使用DriverManager.getConnection()方法打开一个连接,并创建一个Statement对象。接下来,我们使用Statement.executeQuery()方法执行SQL查询,并将结果存储在ResultSet对象中。最后,我们通过ResultSet.next()方法遍历结果集,并使用ResultSet.getXXX()方法获取每个列的值。
以上示例仅供参考,您可以根据您的具体情况进行修改。