学习了如何在 JavaWeb 项目中进行数据库连接操作。通过 JDBC 连接数据库,执行 SQL 查询语句获取数据。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseAccessExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
System.out.println(rs.getString("column_name"));
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}