创建一个带有main的入口类,里边的代码内容:
//链接对象
Connection con=null;
//查询对象
PreparedStatement ps=null;
//结果集对象
ResultSet rs=null;
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydata","root","123456");
//通过sex性别来查询
String sql="SELECT * FROM user WHERE sex = ?";
//获取statement
ps=(PreparedStatement) con.prepareStatement(sql);
ps.setString(1, "2");
//查询输出结果
rs=ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("id")+" "+rs.getString("username"));
}
}catch(Exception e) {
e.printStackTrace();
//关闭连接
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
查询结果
网友评论