JavaWeb+MySQL代码范例
时间: 2024-07-15 11:00:36 浏览: 85
计算机专业毕业设计范例509篇jsp2168网上花店购物商城系统 ssm+mysql idea运行录像.rar
Java Web与MySQL的结合通常涉及到使用Servlet、JSP和JDBC(Java Database Connectivity)进行数据库交互。这里是一个简单的JavaWeb+MySQL的例子,展示了如何连接数据库、执行查询并显示结果:
```java
// MySQL数据库连接(使用JDBC)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLConnection {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
public static void main(String[] args) {
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM mytable";
// 执行查询
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
System.out.println(rs.getString("column1") + ", " + rs.getString("column2"));
}
rs.close(); // 关闭结果集
stmt.close(); // 关闭Statement
conn.close(); // 关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 在JSP中展示结果
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>MyTable Results</h2>
<%
try {
// 连接数据源,这里假设使用了Spring或MyBatis等框架
List<MyData> data = getMyDataFromDatabase();
for (MyData item : data) {
out.println(item.getColumn1() + " - " + item.getColumn2());
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
阅读全文