目前学习的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>