JAVA连接数据库,查询功能怎么写

2024-11-29 19:39:12
推荐回答(1个)
回答1:

public class JdbcNoarg {

//查坦春薯询一行数据

public void getQueryNoargOne(){

JdbcMysqlPool jdbc = new JdbcMysqlPool();

Connection con=null;

Statement st = null;

String sql;

ResultSet rst = null;

try {

//获森大取数据库连接

con = jdbc.getConnection();

//在连接里打开一条通道createStatement,返回Statement对象

st = con.createStatement();

sql = "select *from student";

//把我们想要结果sql语句发送让者给数据库,数据库返回的数据用java ResultSet来接收

rst= st.executeQuery(sql);

//获取结果集的第一行数据9

rst.first();

//获取结果集指定列的数据

String name = rst.getString("name");

String interest = rst.getString("interest");

System.out.println("name:"+name+";interest:"+interest);

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

if(rst!=null)

rst.close();

if(st!=null)

st.close();

if(con!=null)

con.close();

} catch (Exception e2) {

e2.printStackTrace();

}

}

}