这篇“JSP如何连接SQL数据库”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JSP如何连接SQL数据库”文章吧。
(1)导入sql包
<%@ page import = "java.sql.*" %>
(2)加载数据库驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
(3)建立数据库连接
Connection ct=DriverManager.getConnection( url,user,password);
这里的url,user,password 。 url 指定数据库,user 是你数据库成员的用户名,password 是密码,一会看下面的完整代码就明白了。
(4)发送sql语句(两种方法)
方法一:statement
执行查询功能(select)
Statement stmt = ct.createStatement(); String sql = "select * from 账号"; // 执行数据库查询语句
rs = stmt.executeQuery(sql);
执行更新增删改操作(insert,delete,update)
Statement stmt = ct.createStatement();
String sql = "update 学生表 set 学号='201601000' where 姓名 = '张三'";
stmt.executeUpdate(sql);
方法二:preparedstatement
String sql = "update 学生表 set 学号=? where 姓名 = ?";
st.executeUpdate(sql);
PreparedStatement ps = ct.prepareStatement(sql);
ps.setString(1, "201601000");
ps.setString(2, "张三");
ps.executeUpdate();
(5)如果查询的话处理结果集(ResultSet)
查看完整代码:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
PreparedStatement ps = null;
Connection ct = null;
ResultSet rs = null;
String url = "jdbc:sqlserver://localhost:1433;databaseName=test";
String user="sa"; //超级管理员
String password="***********"; //密码
try { //1.加载驱动
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("加载驱动成功!");
}catch(Exception e) {
e.printStackTrace();
System.out.println("加载驱动失败!");
} try {
//2.连接
ct=DriverManager.getConnection( url,user,password);
System.out.println("连接数据库成功!");
}catch(Exception e) {
e.printStackTrace();
System.out.println("连接数据库失败!");
} out.println("select * from emp"+"<br>");
/*尝试查询数据库*/
try{
Statement stmt = ct.createStatement();
String sql = "select * from emp"; // 执行数据库查询语句
rs = stmt.executeQuery(sql); while (rs.next()) {
String id = rs.getString("eno");
String name = rs.getString("ename");
String age = rs.getString("sex");
out.println("eno:" + id +"\t"+ "ename:" + name +"\t"+"sex:" + age+"<br>");
} if (rs != null) {
rs.close();
rs = null;
} if (stmt != null) {
stmt.close();
stmt = null;
} if (ct != null) {
ct.close();
ct = null;
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
%>
</body>
</html>
以上就是关于“JSP如何连接SQL数据库”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。