strtus2连接mysql
时间: 2023-03-31 09:02:28 浏览: 55
可以使用 JDBC 驱动程序连接 MySQL 数据库,具体步骤如下:
1. 下载 MySQL JDBC 驱动程序,将其添加到项目的 classpath 中。
2. 在 Struts2 的配置文件中配置数据源,例如:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
3. 在 Action 中使用 JDBC 连接数据库,例如:
public class MyAction extends ActionSupport {
private Connection conn;
private Statement stmt;
private ResultSet rs;
public String execute() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
return SUCCESS;
}
}