JSP连接数据库

JSP连接数据库,注意读者需要提前安装好mysql数据库,并且把相应的驱动程序下载安装好。本人是mysql5.0.

代码如下:

<%@ page language="java" import="java.sql.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
String url ="jdbc:mysql://localhost:3306/testdb"; //数据库连接字符串
Class.forName("com.mysql.jdbc.Driver").newInstance(); //加载驱动程序
Connection conn= DriverManager.getConnection(url,"root","rootcc111"); //建立连接
String sql="select * from users where username=? and password=?";
PreparedStatement pStmt = conn.prepareStatement(sql);
String username=request.getParameter("username");
String password=request.getParameter("password");
pStmt.setString(1,username);
pStmt.setString(2,password);
ResultSet rs=pStmt.executeQuery( );
if( rs.next() ){
out.print("你已登录,欢迎"+username);
}
else{
out.print("用户名或密码错");
}
//关闭
rs.close(); pStmt.close(); conn.close(); %>

</body>
</html>

 

 

注意:对于JavaEE,直接用jsp连接数据库是不规范的写法,代码重复量大,规范写法是放到模型控制层中的DAO(Data Access Object)层中。

对于此写法本人github上有源码,读者可以自行阅读。

下面是链接:

https://github.com/jiang-congcong/JavaEE-check-online-update1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值