2021-05-28 java访问数据库的方式

本文介绍了使用Java直接通过JDBC、JavaBean以及连接池技术连接MySQL数据库的方法。包括了驱动注册、数据库配置信息的读取以及连接池的设置和使用。示例中展示了如何在Java代码中建立数据库连接,以及如何关闭连接资源。
摘要由CSDN通过智能技术生成

目前学习的java访问数据库的方式,如果以后学到了新的会补充<(^-^)>
利用JDBC连接MySQL数据库

        //驱动程序名
        String drivrName= "com.mysql.jdbc.Driver";
        //数据库用户名
		String userName="root";
		//密码
		String userPwd="1106";
		//数据库名
		String dbNAme="lianxi";
		
		String url1="jdbc:mysql://localhost:3306/"+dbNAme;
		String url2="?user="+userName+"&password="+userPwd;
		String url3="&useUnicode=true&characterEncoding=UTF-8";
		//形成带数据库的读写编码的数据库连接字
		String url=url1+url2+url3;
		//加载并注册数据库
		Class.forName(drivrName);
		Connection conn=DriverManager.getConnection(url);

用JavaBean设计访问数据库

//db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=1106
//JdbcUtil.java
public final class JdbcUtil {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	private static Properties pr=new Properties();
	private JdbcUtil(){	}
	static {
		try{
			pr.load(JdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));
			driver=pr.getProperty("driver");
			url=pr.getProperty("url");
			user=pr.getProperty("username");
			password=pr.getProperty("password");
			Class.forName(driver);	
		}catch(Exception e){
			throw new ExceptionInInitializerError(e);
		}
	}
	public static Connection getConnection() throws SQLException
	{
		return DriverManager.getConnection(url,user,password);
	}
	public static void free(ResultSet rs,Statement st,Connection conn) throws Exception
	{
		if(rs!=null){
			rs.close();
		}
		if(st!=null){
			st.close();
		}
		if(conn!=null){
			conn.close();
		}
	}
}

使用连接池技术访问数据库

//context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/mysql"
type="javax.sql.DataSource"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/lianxi"
username="root"
password="1106"
maxActive="4"
maxIdle="2"
maxWait="6000"
/>

</Context>

这里的maxActive:最大连接数据库连接数
maxIdle:最大等待连接中的数量
maxWait:最大等待毫秒数, 单位为 ms, 超过时间会出错误信息

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MySQL数据源应用</title>
</head>
<body>
<% 
DataSource ds=null;
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
InitialContext ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
conn=ds.getConnection();

%>
</body>
</html>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值