您的位置:首页 > 编程语言 > Java开发

2016-04-22jdbc-mysql-java

2016-04-22 22:58 471 查看
//需求:遍历学生表的姓名
@Test
public void test() throws SQLException, ClassNotFoundException{
//注册驱动
//DriverManager.registerDriver(new Driver());
String url = "jdbc:mysql://localhost:3306/mytest";
String user = "root";
String password = "123456";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
//获得连接
conn = DriverManager.getConnection(url, user, password);
//发送sql语句的对象
String sql = "select * from student;";
stmt = conn.prepareStatement(sql);
//结果集
rs = stmt.executeQuery();
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}
} catch (Exception e) {
}finally{
try {
if(rs != null){
rs.close();
}
rs = null;
} catch (Exception e2) {
}
try {
if( stmt != null){
stmt.close();
}
stmt = null;
} catch (Exception e2) {
}
try {
if( conn != null){
conn.close();
}
conn = null;
} catch (Exception e2) {
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: