六祎-使用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();
		}

 

全部评论

相关推荐

我也曾抱有希望:说的好直白
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务