package com.zhiru;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class Student {
private String sno, sname, ssex;
private int sage;
public Student() {
super();
}
public Student(String no, String name, String sex, int age) {
this.sno = no;
this.sname = name;
this.ssex = sex;
this.sage = age;
}
public void setSno(String no) {
this.sno = no;
}
public void setSname(String name) {
this.sname = name;
}
public void setAge(int age) {
this.sage = age;
}
public String getSno() {
return sno;
}
public String getName() {
return sname;
}
public int getAge() {
return sage;
}
public String getSex() {
return ssex;
}
}
public class MyDao {
/*
* dao:数据访问对象 将对数据库的操作封装为对一个类的操作。 它处于数据库之上,业务逻辑之下
* 包括的功能:加载驱动,获取数据库连接,添加,查询,删除用户,查询所有用户。
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取数据库连接
public Connection getConnection() {
try {
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
// 关闭数据库连接
public void release(ResultSet rs, Statement s, Connection con)
throws SQLException {
if (rs != null) {
rs.close();
}
if (s != null) {
s.close();
}
if (con != null) {
con.close();
}
}
public Student getStudentBySno(String mysno) throws SQLException {
ResultSet rs = null;
Connection con = null;
PreparedStatement ps = null;
String sql = "select * from student where sno=?";
try {
con = this.getConnection();
ps = con.prepareStatement(sql);
ps.setString(1, mysno);
rs = ps.executeQuery();
if (rs.next()) {
Student stu = new Student(rs.getString("sno"),
rs.getString("sname"), rs.getString("ssex"),
rs.getInt("sage"));
return stu;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.release(rs, ps, con);
}
return null;
}
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
MyDao md = new MyDao();
Student stu = md.getStudentBySno("001");
System.out.println(stu.getSno() + "---" + stu.getName() + "---"
+ stu.getAge() + "---" + stu.getSex());
}
}