html连接mysql数据库用java
时间: 2023-11-13 22:16:46 浏览: 36
连接 MySQL 数据库需要使用 Java 代码,HTML 本身不支持连接数据库。以下是一个连接 MySQL 数据库并查询数据的 Java 代码示例:
```
import java.sql.*;
public class ConnectMySQL {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载 JDBC 驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password");
// 创建 SQL 语句
String sql = "SELECT * FROM users";
// 创建 Statement 对象
stmt = conn.createStatement();
// 执行查询
rs = stmt.executeQuery(sql);
// 输出结果
while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("Name: " + name + ", Email: " + email);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// 关闭连接
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码中,需要将 "localhost"、"database"、"username"、"password" 替换为 MySQL 数据库的实际信息。另外,需要在程序中添加 MySQL 驱动程序的 JAR 包。该 JAR 包可以在 MySQL 官方网站上下载。
需要注意的是,为了保证安全性,需要对用户输入的数据进行验证和过滤,以防止 SQL 注入等攻击。