Java实现查询功能的具体方法如下:使用JDBC连接数据库,获取对象。
Java实现查询功能的具体方法如下:
1. 使用JDBC连接数据库,获取Connection对象。
2. 创建一个Statement对象,用于执行SQL语句。
3. 使用Statement对象的executeQuery()方法执行SQL查询语句,并获取ResultSet对象。
4. 遍历ResultSet对象,获取查询结果。
5. 关闭数据库连接。
以下是一个示例代码:
//创建数据库连接
Connection conn = null;
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="123456";
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
conn=DriverManager.getConnection(url,user,password);
//创建Statement对象
Statement stmt = conn.createStatement();
//执行查询语句
String sql = "select * from student where id = 1";
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.println("id:"+id+" name:"+name+" age:"+age);
}
//关闭连接
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(23条)