JDBC的前世今生
“请必须要有自信,你就是一道风景,没必要在别人风景里面仰视。”你好,我是梦阳辰,快来和我一起学习吧!
文章目录
01.JDBC是什么?
概念:Java DataBase Connectivity ,java数据库连接,Java语言操作数据库。
JDBC本质:sun公司定义的一套操作所有关系型数据库的接口。各个数据库厂商去实现这套接口(提供数据库驱动jar包)。我们可以使用这套接口(jdbc)编程,真正执行的代码时驱动jar包中的实现类。但我们只需要面向接口编程。
02.JDBC快速入门
步骤:
1.下载驱动:去你使用的数据库厂商的官网找到你要使用的数据库版本对应的版本驱动,下载驱动。
2.将驱动jar包导入项目
1.赋值mysql-connector-java-5.1.xx-bin.jar到项目的lib目录下。
然后单击目录右键–>Add as Library。
3.注册驱动(告诉程序你用的是哪个厂商,哪个版本的数据库)
4.获取数据库连接对象(Connetion)(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭)
5.定义sql
6.获取执行sql语句的对象(Statement)(专门执行sql语句的对象)
7.执行sql,接受返回结果
8.处理结果
9.释放连接
注意:用文本编辑器开发,需要配置环境变量到classpath中。
如果使用IDEA工具的时候,不需要配置classpath环境变量,按要求导入jar包到项目即可。
@WebServlet("/com/teaching/case631/JDBC")public class JDBC extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public JDBC() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); Connection conn =null; Statement stat = null; try { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.设置连接参数,url,user,password String url = "jdbc:mysql://localhost:3306/teaching"; String user ="root"; String password ="xxxx"; String useUnicode = "true";//设置编码 String characterEncoding = "UTF8"; /*url="jdbc:mysql://localhost:3306/teaching" +"?user=root" +"&password="xxxxx" +"&userUnicode=true" +"&characterEncoding=UTF8"; */ //conn = DriverManager.getConnection(url); //3.获取数据库连接 conn = DriverManager.getConnection(url,user,password); stat = conn.createStatement(); //5.定义sql语句 String sql = "update student set name = '张三' where name='梦阳辰'"; //6.利用载体执行SQL语句 int count = stat.executeUpdate(sql); //7.处理返回结果 if(count>0) { out.print("连接数据库成功!"); }else { out.print("连接数据库失败!"); } } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //7.关闭连接 if(stat!=null) { try { stat.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( conn !=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
查询:
@WebServlet("/com/teaching/case631/JDBC")public class JDBC extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public JDBC() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); Connection conn =null; Statement stat = null; ResultSet rs = null; try { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.设置连接参数,url,user,password String url = "jdbc:mysql://localhost:3306/teaching"; String user ="root"; String password ="0910"; String useUnicode = "true"; String characterEncoding = "UTF8"; //3.获取数据库连接 conn = DriverManager.getConnection(url,user,password); stat = conn.createStatement(); //5.定义sql语句 String sql = "select * from student"; //6.利用载体执行SQL语句 rs = stat.executeQuery(sql); //7.处理返回结果 while(rs.next()){ int id = rs.getInt("id"); String sequence = rs.getString("sequence"); String name = rs.getString("name"); String sex = rs.getString("sex"); Date birthday = rs.getDate("birthday"); out.println(id+" "+sequence+" " +name+" "+sex+" "+birthday); } } catch (ClassNotFoundException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //7.关闭连接 if(rs!=null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stat!=null) { try { stat.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if( conn !=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}
03.JDBC中的各个类和接口
JDBC API主要位于java.sql包下。
Dirver接口是所有JDBC驱动程序必须实现的接口,该接口专门提供给数据库厂商使用。编写运行程序记得,一定要先将对应数据库厂商的jar包导入项目的classpath中。
1.DriverManager类(驱动管理对象)
功能:
1).注册驱动(告诉程序使用哪一个驱动jar)
//注册与给定的驱动程序 DriverManager static void registerDriver(Driver driver, DriverAction da) //写代码的时候使用:(在驱动5之后可以不写) Class.forName("com.mysql.jdbc.Driver"); //将类加载置内存,一些代码自动执行(静态代码块)
com.mysql.jdbc.Driver的静态代码块:
static { try { //真正注册驱动的程序 java.sql.DriverManager.registerDriver(new Driver()); } catch (SQLException E) { throw new RuntimeException("Can't register driver!"); } }
2.)获取数据库连接
//尝试建立与给定数据库URL的连接static Connection getConnection(String url, String user, String password)
url:
jdbc:mysql:// 协议
127.0.0.1 IP地址
3306 mysql数据库端口号
teaching 数据库
如果主机是本机,端口号是3306,则主机ip和端口号可以不写。
2.Connection接口(数据库连接对象)
功能:
1).获取执行sql的对象。
//创建一个 Statement对象,用于将SQL语句发送到数据库Statement createStatement() //创建一个 PreparedStatement对象,用于将参数化的SQL语句发送到数据库PreparedStatement prepareStatement(String sql)
2).事物管理
开启事务
void setAutoCommit(boolean autoCommit) 将此连接的自动提交模式设置为给定状态,false,即为开启事务
提交事务
void commit()
回滚事务
void rollback()
3.Statement接口(执行sql的对象)
用于执行静态SQL语句并返回其生成的结果的对象。
boolean execute(String sql) ;//使用不多 执行给定的SQL语句,这可能会返回多个结果 int executeUpdate(String sql) ;DML语句 执行给定的SQL语句,这可能是 INSERT, UPDATE,或 DELETE语句, 或者不返回任何内容,如SQL DDL(create,alter,drop)语句的SQL语句。 返回值为影响的行数,可以用来判断DML语句是否执行成功。 ResultSet executeQuery(String sql) ; 执行给定的SQL(select)语句,该语句返回单个 ResultSet对象。
练习:
1.student表 添加一条记录
2.student表 修改一条记录
3.student表 删除一条记录
public class JdbcTest2 { public static void main(String[] args) { Connection conn = null; Statement stat = null; //1.注册驱动 try { Class.forName("com.mysql.jdbc.Driver"); //2.获取连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910"); //3.获取执行sql对象 stat = conn.createStatement(); //4.定义sql语句 //String sql = "insert into student(sequence,name,sex,birthday) values('12341234','张三','男','1999-10-18')"; //String sql = "update student set name='李四' where name = '张三'"; String sql = "delete from student where name ='李四'"; //5.执行sql int count = stat.executeUpdate(sql); System.out.println(count); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //关闭资源 try { if(stat!=null){ stat.close(); } if(conn!=null){ conn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } }}
4.ResultSet接口(结果集对象)
表示数据库结果集的数据表,通常通过执行查询数据库的语句生成.
封装结果集对象:
1.next() //:游标向下移动一行//获取数据(只能获取某行某列的数据,不能获取整行)参数可以为列数(从1开始),也可以为列名2.getXxx(int columnIndex);Xxx代表数据类型。 String getString(int columnIndex) 这个检索的当前行中指定列的值 ResultSet对象为 String的Java编程语言。 String getString(String columnLabel) 这个检索的当前行中指定列的值 ResultSet对象为 String的Java编程语言。
遍历结果集:
boolean next() ;//如果有数据返回true,没有false
public class JdbcTest3 { public static void main(String[] args) { Connection conn = null; Statement stat = null; ResultSet rs = null; //1.注册驱动 try { Class.forName("com.mysql.jdbc.Driver"); //2.获取连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910"); //3.获取执行sql对象 stat = conn.createStatement(); //4.定义sql语句 //String sql = "insert into student(sequence,name,sex,birthday) values('12341234','张三','男','1999-10-18')"; //String sql = "update student set name='李四' where name = '张三'"; String sql = "select * from student"; //5.执行sql rs = stat.executeQuery(sql); //6.处理结果集 //6.1让游标向下移动一行 while(rs.next()){ int id = rs.getInt(1); String name = rs.getString("name"); Sy 8000 stem.out.println(id+"----"+name); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //关闭资源 try { if(rs!=null){ rs.close(); } if(stat!=null){ stat.close(); } if(conn!=null){ conn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } }}
练习:
定义一个方法,查询Studnet表的数据将其封装为对象,然后装载集合,返回。
1.定义Student类(一个表就相当于一个类)
2.定义public List findAll(){}
3.实现方法 select xx,xx,xxx from Student;
student类
/** * javaBean */public class Student { private Integer id;//为防止数据库字段为空,定义为应用数据类型 private String sequence; private String name; private String sex; private Date birthday; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSequence() { return sequence; } public void setSequence(String sequence) { this.sequence = sequence; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Student{" + "id=" + id + ", sequence='" + sequence + '\'' + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; }}
/** * 定义一个方法,查询Studnet表的数据将其封装为对象,然后装载集合,返回 */public class JdbcTest4 { public static void main(String[] args) { List<Student> list= new JdbcTest4().findAll();//对象.方法 System.out.println(list); System.out.println(list.size()); } public List<Student> findAll(){ Connection conn = null; Statement stat = null; ResultSet rs = null; List<Student> list = new ArrayList<>(); //1.注册驱动 try { Class.forName("com.mysql.jdbc.Driver"); //2.获取连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teaching","root","0910"); //3.获取执行sql对象 stat = conn.createStatement(); //4.定义sql语句 String sql = "select id,sequence,name,sex,birthday from student"; //5.执行sql rs = stat.executeQuery(sql); //6.处理结果集 //6.1让游标向下移动一行 Student student = null; while (rs.next()){ int id = rs.getInt(1); String sequence = rs.getString("sequence"); String name = rs.getString("name"); String sex = rs.getString("sex"); Date birthday = rs.getDate("birthday"); //创建student对象,赋初值 student = new Student(); student.setId(id); student.setSequence(sequence); student.setName(name); student.setSex(sex); student.setBirthday(birthday); //装载集合 list.add(student); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //关闭资源 try { if(rs!=null){ rs.close(); } if(stat!=null){ stat.close(); } if(conn!=null){ conn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } return list; }}
可以写JDBC工具类,简化JDBC连接数据的操作。
采用配置文件,存储url,user,password等。
04.PreparedStatement接口(Statement的子接口)
Statement对象,执行sql会存在sql注入问题。
'a' or 'a' = 'a'
SQL注入问题:在拼接sql时,有一些sql的特殊关键字参与字符串的拼接。会造成安全性问题。
2.解决sql注入问题:使用PreparedStatement对象来解决。
PreparedStatement对象采取预编译。
SQL语句已预编译并存储在PreparedStatement对象中。 然后可以使用该对象多次有效地执行此语句。
参数使用占位符
步骤:
1.下载驱动:去你使用的数据库厂商的官网找到你要使用的数据库版本对应的版本驱动,下载驱动。
2.将驱动jar包导入项目
1.赋值mysql-connector-java-5.1.xx-bin.jar到项目的lib目录下。
然后单击目录右键–>Add as Library。
3.注册驱动(告诉程序你用的是哪个厂商,哪个版本的数据库)
4.获取数据库连接对象(Connetion)(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭)
5.定义sql
采取占位符?
select * from student where username = ? and password =?;
6.获取执行sql语句的对象(PreparedStatement)(专门执行sql语句的对象)
创建一个 PreparedStatement对象,用于将参数化的SQL语句发送到数据库 PreparedStatement prepareStatement(String sql)
7.给占位符赋值
setXxx(参数1,参数2) 参数1:?的位置编码 从1开始 参数2:值
8.执行sql,接受返回结果(不需要参数sql)
9.处理结果
10.释放连接
05.JDBC控制事务
JDBC控制事务:
**事务:**一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。
2.操作:
开启事务
提交事务
回滚事务
3.使用connection对象来管理事务
开后事务 : setAutoCommit(boolean autoCcommit) :调用该方法设置参数为false,即开起事务。
提交事务: commit()
回滚事务: rollback( )
Give up worrying about what others think of you。What they think isn’t important.What is important is how you feel about yourself.
这篇文章也许对你有用:
- FileNotFoundException: Could not open ServletContext resource [/jdbc.properties]
- SQL Server 2000 JDBC驱动的完整安装及测试说明
- java操作数据库的演进jdbc-datasource-hibernate-spring
- 传统jdbc的缺点
- spring boot(10)-tomcat jdbc连接池
- JDBC介绍
- JDBC- exercise-2 通过htttp 访问 数据库,返回一个JSON格式的相应信息
- JDBC的基本操作
- JDBC连接驱动
- JDBC简单介绍以及Java连接MySQL数据库
- Hibernate 抛出的 Could not execute JDBC batch update
- JDBC核心API
- JDBC statement与preparedStatement
- MySQL第二天早上第一次连接超时报错,解决方法com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
- HikariPool-1 - jdbcUrl is required with driverClassName.
- 如何简化JDBC代码
- JDBC组件 Druid
- jdbc连接数据库出现的问题,Statement一直为null
- SQL SERVER 的前世今生--各版本功能对比
- JDBC连接数据库和释放连接