您的位置:首页 > 数据库 > MySQL

JSP——JDBC连接数据库(MySQL)

2020-02-02 14:29 1351 查看

JDBC连接数据库

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>连接数据库</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>
<%
String url="jdbc:mysql://localhost/test";
String username="root";
String password="123456";
String sql=null;
Connection conn=null;
Statement stmt=null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
out.println("加载驱动器类时出现异常");
}

try{
conn=DriverManager.getConnection(url,username,password);
}catch(SQLException e){
out.print("连接数据库的过程中出现SQL异常");
}

if(conn==null)
out.println("连接数据库失败");
else
out.println("连接数据库成功");

try{
conn.close();
}catch(SQLException e){
out.print("关闭数据库连接时出现SQL异常");
}
%>
</body>
</html>
  • 点赞
  • 收藏
  • 分享
  • 文章举报
可一z可再 发布了18 篇原创文章 · 获赞 1 · 访问量 246 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: