六祎-使用JDBC连接数据库(适合初学者)
StudentsDao.java
public int id;
public String sname;
public String sgender ;
public int sage;
public int grade;
public String smarriage;
StudentsTest.java
String url="jdbc:mysql://localhost:3306/lz?useUnicode&chacter=utf8";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, "root", "12345678");
String sql="select sname from students";
PreparedStatement pstm = conn.prepareStatement(sql);
ResultSet rs = pstm.executeQuery();
List lists= new ArrayList<StudentsDao>();
while(rs.next()) {
StudentsDao st = new StudentsDao();
st.sname=rs.getString("sname");
lists.add(st);
}
for( int i = 0 ; i < lists.size(); i ++) {
StudentsDao st = (StudentsDao) lists.get(i);
System.out.println(st.sname);
}
rs.close(); //结果集
pstm.close();
conn.close(); //数据库连接
//System.out.println(conn);
} catch ( Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}