java_web学习第九天(JDBC数据库驱动------基础知识)

JDBC:jaba data base connectivity 数据库驱动。
	由sun公司提供的为统一对数据库的操作。

传统的数据库操作是:
	应用程序--->Mysql(Oracle)驱动--->Mysql(oracle)
jdbc对数据库的操作:
	应用程序--->jdbc--->Mysql(Oracle)驱动--->Mysql(oracle)

传统和jdbc对比,中间多了一步操作jdbc。
优势:应用程序跟具体的驱动器分离,我只要进行数据的操作,而不管底层的数据驱动用的是哪个,即应用程序对数据的操作跟具体的数据库驱动无关,而且对数据的操作放在了jdbc上,这样我只要写一套代码,就可以连接多个驱动。

使用JDBC:
	1.注册数据库的驱动
	2.获取数据库的连接
	3.获取Statement对象,用于执行sql语句。
	4.使用Statement对象执行sql语句。
	5.关闭资源。
在Mysql中常见一个date数据库,在这个数据库中创建表student(name,password);
package com.enterise.always.driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class HandleData {
	
	public static Connection getConnection(){
		Connection conn = null;
		try {
			//1.注册驱动
//			DriverManager.registerDriver(new Driver());
			Class.forName("com.mysql.jdbc.Driver");
			
			//2.获取连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/date", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	
	/**
	 * 增
	 * @param student
	 * @throws SQLException
	 */
	public static void insert(Student student) throws SQLException{
		Connection conn = getConnection();
		Statement statement = conn.createStatement();
		int insertResult = statement.executeUpdate("INSERT INTO student VALUES('"+student.getName()+"','"+student.getPassword()+"')");
		System.out.println("insertResult------------->"+insertResult);
		
		statement.close();
		conn.close();
	}
	/**
	 *删
	 * @param student
	 * @throws SQLException
	 */
	public static void delete(Student student) throws SQLException{
		Connection conn = getConnection();
		Statement statement = conn.createStatement();
		int deleteResult = statement.executeUpdate("DELETE FROM student WHERE name='"+student.getName()+"'");
		System.out.println("deleteResult---------------->"+deleteResult);
		
		statement.close();
		conn.close();
	}
	
	/**
	 * 改
	 * @param student
	 * @throws SQLException
	 */
	public static void update(Student student) throws SQLException{
		Connection conn = getConnection();
		Statement statement = conn.createStatement();
		int updateResult = statement.executeUpdate("UPDATE student set password='"+student.getPassword()+"' WHERE name='"+student.getName()+"'");
		System.out.println("updateResult---------------->"+updateResult);
		
		statement.close();
		conn.close();
	}
	
	/**
	 * 查
	 * @throws SQLException
	 */
	public static void getAll() throws SQLException{
		Connection conn = getConnection();
		Statement statement = conn.createStatement();
		ResultSet set = statement.executeQuery("SELECT * FROM student");
		
		while(set.next()){
			String name = set.getString("name");
			String password = set.getString("password");
			
			System.out.println("name------------>"+name);
			System.out.println("password----------->"+password);
		}
		set.close();
		statement.close();
		conn.close();
	}

}
在servlet中调用相应的方法。
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

Student student = new Student("wu","1234");
try {
HandleData.insert(student);

HandleData.insert(new Student("chen","1234"));

HandleData.update(new Student("chen","chen"));

HandleData.getAll();

HandleData.delete(student);

} catch (SQLException e) {
e.printStackTrace();
}
}
细节问题:
	1.数据库的驱动方式有两种:
		1.DriverManager.registerDriver(new Driver());
		2.Class.forName("com.mysql.jdbc.Driver");
	优缺点:
		registerDriver:如果采用此种方式,会导致驱动程序注册两次,也就是在内存中会有两个Driver对象。
		采用此种方式不会导致驱动对象在内存中重复出现,并且采用此种方式,程序仅仅只需要一个字符串,不需要import驱动的API,这样可使程序不依赖具体的驱动,使程序的灵活性更高。
	2.数据库URL
		URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:jdbc:mysql://localhost:3306/date
			jdbc :协议。
			mysql :子协议。
			localhost:3306 :主机:端口。
			date:数据库的database名称。
	URL后面也可以跟上参数,比如数据库的用户名、密码和一些编码:
		jdbc:mysql://localhost:3306/date?user=root&password=root&characterEncoding=UTF-8
	3.Connection对象:
		Jdbc程序中的Connection,它用于代表数据库的连接,Connection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的.
		常用方法:
			createStatement():创建向数据库发送sql的statement对象。
			prepareStatement(sql) :创建向数据库发送预编译sql的PrepareSatement对象。
			prepareCall(sql):创建执行存储过程的callableStatement对象。 
			setAutoCommit(boolean autoCommit):设置事务是否自动提交。 
			commit() :在链接上提交事务。
			rollback() :在此链接上回滚事务。
	4.Statement对象:
		Jdbc程序中的Statement对象用于向数据库发送SQL语句.
		常用方法:
			execute(String sql):用于向数据库发送任意sql语句
			executeQuery(String sql) :只能向数据发送查询语句。
			executeUpdate(String sql):只能向数据库发送insert、update或delete语句

			addBatch(String sql) :把多条sql语句放到一个批处理中。
			executeBatch():向数据库发送一批sql语句执行。 

			//执行一批sql语句
			statement.addBatch("INSERT INTO student(name,password) VALUES('guoguo','guoguo')");
			statement.addBatch("UPDATE student set password='12345' WHERE name='guoguo'");
			statement.addBatch("DELETE FROM student WHERE name='guoguo'");
			int[] executeBatch = statement.executeBatch();
			for(int i = 0;i<executeBatch.length;i++){
				System.out.println("executeBatch--------->"+executeBatch[i]);
			}
	5.ResultSet结果集 在查询中会返回结果集。
		Jdbc程序中的ResultSet用于代表Sql语句的执行结果。Resultset封装、执行结果时,采用的类似于表格的方式。ResultSet 对象维护了一个指向表格数据行的游标,初始的时候,游标在第一行之前,调用next() 方法,可以使游标指向具体的数据行,进行调用方法获取该行的数据。
		ResultSet set = statement.executeQuery("SELECT * FROM student");
		
		while(set.next()){
			String name = set.getString("name");
			String password = set.getString("password");
			
			System.out.println("name------------>"+name);
			System.out.println("password----------->"+password);
		}

	6.PreperedStatement对象:
		PreperedStatement对象是Statement的子类,它的实例对象可以通过调用Connection.preparedStatement()方法获得,相对于Statement对象而言:
		PreperedStatement可以避免SQL注入的问题。
		Statement会使数据库频繁编译SQL,可能造成数据库缓冲区溢出。PreparedStatement 可对SQL进行预编译,从而提高数据库的执行效率。
		并且PreperedStatement对于sql中的参数,允许使用占位符的形式进行替换,简化sql语句的编写。
		PreparedStatement对象还可以防止sql注入
	7.释放资源
		Jdbc程序运行完后,切记要释放程序在运行过程中,创建的那些与数据库进行交互的对象,这些对象通常是ResultSet, Statement和Connection对象。
		特别是Connection对象,它是非常稀有的资源,用完后必须马上释放,如果Connection不能及时、正确的关闭,极易导致系统宕机。Connection的使用原则是尽量晚创建,尽量早的释放。

		为确保资源释放代码能运行,资源释放代码也一定要放在finally语句中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值