public class SelectProcess {
public static void main(String[] args) {
//设置执行操作语句
String sql = "select * from tbl_user";
Connection conn = null; //代表当前数据库连接
Statement statement = null; //数据库发送sql语句
ResultSet resultset = null; //代表结果集,封装了从数据库得到的数据
while(resultset.next()){
System.out.print(resultset.getInt("id")+" ");
System.out.print(resultset.getString("name")+" ");
System.out.print(resultset.getString("password")+" ");
System.out.print(resultset.getString("email")+" ");
System.out.println();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
resultset.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//设置执行操作语句
String sql = "select * from tbl_user";
Connection conn = null; //代表当前数据库连接
Statement statement = null; //数据库发送sql语句
ResultSet resultset = null; //代表结果集,封装了从数据库得到的数据
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//打开连接
statement = conn.createStatement();
//执行操作
while(resultset.next()){
System.out.print(resultset.getInt("id")+" ");
System.out.print(resultset.getString("name")+" ");
System.out.print(resultset.getString("password")+" ");
System.out.print(resultset.getString("email")+" ");
System.out.println();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
resultset.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
本文提供了一个使用Java通过SQL查询数据库的具体示例。该示例展示了如何连接到MySQL数据库、执行SELECT语句并打印出查询结果。具体步骤包括加载驱动、建立连接、创建Statement对象、执行查询以及遍历结果集。

被折叠的 条评论
为什么被折叠?



