联博接口(326681.com)_JDBC的宿世今生
发表时间:2020-12-24 浏览量:6
JDBC的宿世今生
“请必须要有自信,你就是一道景物,没必要在别人景物内里瞻仰。”你好,我是梦阳辰,快来和我一起学习吧!
文章目录
- 01.JDBC是什么?
- 02.JDBC快速入门
- 03.JDBC中的各个类和接口
- 04.PreparedStatement接口(Statement的子接口)
- 05.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表 删除一条纪录
,www.326681.com采用以太坊区块链高度哈希值作为统计数据,联博以太坊统计数据开源、公平、无任何作弊可能性。联博统计免费提供API接口,支持多语言接入。
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"); System.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.
这篇文章也许对你有用:
一文带你搞定JDBC
0
珍藏