import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.Statement;
public class JDBCtest {
public static void main(String[] args) {
String sql = "select * from tbl_user";//查询语句SQL
Connection conn=null; //定义一个连接
Statement statement = null; //定义一个语句
ResultSet rs=null; //定义一个结果集
try {
Class.forName("com.mysql.jdbc.Driver"); //定义一个连接数据库驱动
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "");//将链接赋值一个连接mysql的驱动链接
statement =(Statement) conn.createStatement(); //将SQL语句赋值为一个mysql的执行语句
rs=statement .executeQuery(sql); //执行并获得结果集
while(rs.next()){ //一开始指针指向第一个的前一个,每次执行一次之后向后移动一个单位
System.out.print(rs.getInt("id")+" ");
System.out.print(rs.getString("name")+" ");
System.out.print(rs.getString("password")+" ");
System.out.print(rs.getString("email")+" ");
System.out.println();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
rs.close(); //从小到大进行关闭
} catch (Exception e2) {
// TODO: handle exception
}
try {
statement.close();
} catch (Exception e2) {
// TODO: handle exception
}
try {
conn.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
JDBC数据查询
最新推荐文章于 2024-03-05 15:23:35 发布