- 加载驱动
- 打开连接
- 执行查询
- 处理结果
- 清理环境
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JDBCtest {
public static void main(String[] args) {
String sql = "SELECT * from tbl_user";
// 当前的数据库链接;
Connection connection = null;
// 用于向数据库发送sql语句
Statement statement = null;
// 结果集,封装了从数据库查询的数据
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jsp_db", "root", "1078966873");
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.print(resultSet.getInt("id") + " ");
System.out.print(resultSet.getString("name") + " ");
System.out.print(resultSet.getString("password") + " ");
System.out.print(resultSet.getString("email") + " ");
System.out.println();
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}