javaweb使用idea连接MySQL数据库和servlet进行查询数据库内照片操作
时间: 2023-05-28 07:02:53 浏览: 198
步骤如下:
1. 下载安装MySQL数据库,并新建一个数据库;
2. 在IDEA中打开一个JavaWeb项目,新增一个Libraries库中添加MySQL的驱动jar包;
3. 在项目的web目录下创建一个数据库连接的配置文件(比如db.properties),并将连接信息配置好,如下所示:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名
username=数据库用户名
password=数据库密码
4. 在servlet代码中,通过读取配置文件来获取数据库连接及操作:
```
public class MyServlet extends HttpServlet {
private static final String DRIVER;
private static final String URL;
private static final String USERNAME;
private static final String PASSWORD;
static {
Properties properties = new Properties();
InputStream inputStream = MyServlet.class.getResourceAsStream("/db.properties");
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
DRIVER = properties.getProperty("driver");
URL = properties.getProperty("url");
USERNAME = properties.getProperty("username");
PASSWORD = properties.getProperty("password");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
Connection connection = null;
try {
// 加载驱动
Class.forName(DRIVER);
// 获取连接
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
// 执行SQL语句
String sql = "select * from photo";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 从结果集中获取数据
String photoName = resultSet.getString("photo_name");
String photoUrl = resultSet.getString("photo_url");
// 输出数据
out.print("照片名称:" + photoName + ",照片地址:" + photoUrl + "<br/>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
5. 在浏览器中输入访问地址:http://localhost:8080/MyServlet,即可查询到数据库中的照片信息了。
阅读全文