我们选择直接用jsp连接数据库。规范写法其实是放到模型控制层中的DAO(Data Access Object)层中
步骤
-
导入数据库jar包
-
注册驱动Class.forName("com.mysql.jdbc. Driver");
-
创建连接
String url="jdbc:mysql://localhost:3306/数据库名";
-
创建执行对象
Statement stmt = con.createStatement();
-
操作数据库
代码
定义conn.jsp负责链接数据库
<%@ page language="java" import="java.sql.*"
pageEncoding="UTF-8"%>
<%
Connection conn = null;
Statement stmt = null;
Statement stmt1 = null;
Statement stmt2 = null;
Statement stmt3 = null;
String sDBDriver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/filedb";
try {
//加载数据库驱动
Class.forName(sDBDriver);
//获取数据库链接
conn = DriverManager.getConnection(url, "root", "root");
stmt = conn.createStatement(); //创建连接状态
} catch (Exception e) {
e.printStackTrace();
System.err.println("数据库驱动注册错误信息: " + e.getMessage());
}
%>
标签:jdbc,数据库,jsp,mysql,JSP,连接
From: https://www.cnblogs.com/tfhdm/p/16974612.html