一、JDBC技术简介
在Java web应用程序中,数据库访问是通过Java数据库连接实现的,一种是通过JDBC驱动程序直接连接数据库,另一种是通过连接数据池技术连接数据库。
二、准备工作:下载数据库对应的jar包并导入
导入import java.sql.*;即可。
三、JDBC的基本操作
(1)数据库连接步骤
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建连接
String driverName="com.mysql.jdbc.Driver";
String userName="root";
String userPwd="pass1234";
String dbName="jdbc";
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;
connection = DriverManager.getConnection(url);
System.out.println("创建连接成功!");
//3.写sql
String sql="select* from tb_jdbc";
//4.得到statement对象
statement=connection.prepareStatement(sql);
//5.执行sql 得到结果
resultSet=statement.executeQuery();
//6.处理结果集
while (resultSet.next())
{
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
//7.关闭资源
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if(resultSet!=null) {resultSet.close();}
if(statement!=null) {statement.close();}
if(connection!=null) {connection.close();}
} catch (SQLException se) {
}
}
}
(2)连接的获取
在操作之前必须先获取与数据库的连接。
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/samp_db";
String username = "root";
String password = "";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
(3)插入操作
private static int insert(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getSex());
pstmt.setString(3, student.getAge());
i = pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
(4)更新操作
private static int update(Student student) {
Connection conn = getConn();
int i = 0;
String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
(5)删除操作
private static int delete(String name) {
Connection conn = getConn();
int i = 0;
String sql = "delete from students where Name='" + name + "'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
i = pstmt.executeUpdate();
System.out.println("resutl: " + i);
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
(5)问题思考
1.每次SQL操作都需要建立和关闭连接,这势必会消耗大量的资源开销,如何避免?
分析:可以采用连接池,对连接进行统一维护,不必每次都建立和关闭。事实上这是很多对JDBC进行封装的工具所采用的。
2.Java代码中,传入的数据格式与数据库定义不同怎么办?如把Java的String对象赋值给数据库的tinyint属性。
分析:在执行SQL语句时,数据库会尝试进行转换。根据我的实验,如果用内容为纯字母的String对象传入tinyint的age属性时,会被转化成0。具体转化规则应该和数据库有关。
四、通过连接数据池技术连接数据库
通过连接池技术连接数据库需要两步处理:首先需要配置数据源,然后再程序中通过连接池建立数据库连接,从而再次访问数据库。
1、在服务器上添加MySQL数据库驱动程序
将mysql数据库的驱动程序复制到Tomcat安装路径下的common\lib文件夹中。
2.配置数据源参数
<Context>
<Resource name="jdbc/mysql"
type=javax.sql.DataSource"
auth="Contatiner"
dirverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/数据库名字"
username="用户名“
password="用户密码”
maxActivr="4"
maxIdle="2"
maxWait="6000"/>
</Context>
3.使用连接池技术访问数据库的处理步骤
(1)获取对数据源的引用
Context ctx=new InitalContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
(2)获取数据库连接对象
Connectiion con=ds.getConnection();
(3)返回数据库连接到连接池
con.close();