漫谈jdbc
本文可作为北京尚学堂jdbc课程的学习笔记; 简介 jdbc是什么东西? jdbc全称(Java Database Connectivity java数据库连接) 它是干什么的? 至于它是干什么的,那就应了那句老话了,说来话长.. 很久很久之前,作为用户,我们有c,c++,java...各种语言,另一方面数据库领
本文可作为北京尚学堂jdbc课程的学习笔记;简介
jdbc是什么东西?jdbc全称(Java Database Connectivity java数据库连接)
它是干什么的?
至于它是干什么的,那就应了那句老话了,说来话长..
很久很久之前,作为用户,我们有c,c++,java...各种语言,另一方面数据库领域Oracle,Mysql,DB2,SQLServer也是种类繁多。
为了方便我们用户的使用各大数据库厂商就就建立了自己的API,如下图

看上去还不错哦。
后来,我们还是觉得麻烦,虽然各个厂商有自己的API,但我Oracle和Myaql毕竟不一样呀!作为客户的我们,并不想学习那么多的API,怎么办?
再加一层呗!

至于odbc是微软出的一套东西,干的事情和jdbc一样,就是屏蔽各个数据库的不同!
看上面的图大家就应该明白,各个数据库厂商会开发自己的jdbc jar包。
至此,我们就不需要管各个数据库的差异问题了。(当然,各个数据库的sql语法还有些微的不同,再后来Hibernate出现了,这里我们先不谈)
我们只用了解一个统一的接口,就能方便的使用各个数据库。

编程步骤
LoadDriver
Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.jdbc.Driver").newInstance(); new com.mysql.jdbc.Driver();
我们看这个例子
package load; public class LoadTest { public static void main(String[] args) { try { Class.forName("load.Loaded"); System.out.println("*******"); Class.forName("load.Loaded").newInstance(); System.out.println("*****"); new Loaded(); } catch (ClassNotFoundException |IllegalAccessException|InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } package load; public class Loaded { static{ System.out.println("i am static"); } public Loaded(){ System.out.println("i am constructed"); } }
i am static
*******
i am constructed
*****
i am constructed
大家应该明白了
Class.forName("***"); 会加载一个类,返回的结果是Class类型的,在加载过程中,会执行类中的静态语句块;
Class.forName("***").newInstance(); 它其实和new ***()是一样的,当然类只用加载一次,所以上面调用这行代码的时候没有显示i am static
new ***() 这个和上面那个的区别在于,这个方法可以传递参数,构造不同的类,但是上面的newInstance只能构造无参的对象;
在说的通俗一点,jvm要生成一个类
需要两步,加载与实例化!
第一个方式是加载,后面两个既加载,又实例化(当然,如果前面已经加载了,就不用再加载了)
另外,关于这部分源码基本的分析如com.mysql.jdbc.Driver中到底干了什么,我们后面再说,这里就不多讨论了。
获得Connection
DriverManager.getConnection(url,username,password);
三个参数的意思我就不多说了,这里需要我们注意的其实也就一个url,不过大家也不用死记硬背,知道有这么个东西就ok;
获得Statemment;
Statement st=con.creatStatemnent();获得结果集;
首先我们得说明,这里的结果集是用ResultSet来组织的。ResutSet rs=st.executeQuery("select * from admininfo");
遍历结果集:
while (rs.next()) {System.out.println(rs.getString("Filedname"));
}
这里我得说明一点,即使你想取得数据集中的第一条数据,rs.next()这行也必须有。我们可以理解为,初始情况下resultset内部的"游标"在第一条数据前面,我们得next一下能找到下一条数据!
close
一个原则,后建立的对象先关闭。最基本的jdbc
下面的代码,写的比较全,只有一个要求,背下来!不要说,先看看,以后再说,这是基础!应该全文默写!!
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBC_Test2 { public static void main(String[] args) { Connection conn=null; Statement st=null; ResultSet rs=null; String url="jdbc:mysql://localhost:3306/webexample?useUnicode=true&characterEncoding=UTF-8"; String userName="root"; String passWord=""; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection(url,userName,passWord); st=conn.createStatement(); rs=st.executeQuery("select * from admininfo"); while (rs.next()) { System.out.println(rs.getString("Aname")); } } catch (ClassNotFoundException e) { e.printStackTrace(); //log4j 具体记录 }catch (SQLException e) { e.printStackTrace(); } finally{ try { if (rs!=null) { rs.close(); rs=null; } if (st!=null) { st.close(); st=null; } if (conn!=null) { conn.close(); conn=null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
几个知识点
PreparedStatement
其实Statement本身已经够用了,不过有点不方便,哪里不方便?看下面的例子:
我想将一条数据插入到数据库中如下
String name="董磊峰"; int id=16; String sql="insert into admininfo (Aname,Aid) values('"+name+"',"+id+") "; st.executeUpdate(sql);
所以有了PreparedStatement,它也是一个接口,继承自Statement。
其用法为
String name="董磊峰2"; int id=18; String sql="insert into admininfo (Aname,Aid) values(?,?)"; PreparedStatement st=conn.prepareStatement(sql); st.setString(1, name); //给第一个栏位注入String型的数值name 这个不是从0开始 st.setInt(2, id); st.execute();
批处理问题
如果我想执行多条sql语句怎么办?使用Statement
String name="董磊峰2"; int id=154; int id2=487; String sql="insert into admininfo (Aname,Aid) values('"+name+"',"+id+") "; String sql2="insert into admininfo (Aname,Aid) values('"+name+"',"+id2+") "; System.out.println(sql); st=conn.createStatement(); st.executeUpdate(sql); st.executeUpdate(sql2);
String name="董磊峰2"; int id=48; String sql="insert into admininfo (Aname,Aid) values(?,?)"; System.out.println(sql); st=conn.prepareStatement(sql); st.setString(1, name); st.setInt(2, id); st.execute(); st=conn.prepareStatement(sql); st.setString(1, name); st.setInt(2, id+1); st.execute();
看新的方法
使用Statement
st=conn.createStatement(); st.addBatch("insert into admininfo (Aname,Aid) values('"+name+"',"+id+") "); st.addBatch("insert into admininfo (Aname,Aid) values('"+name2+"',"+id2+") "); st.executeBatch();
String sql="insert into admininfo (Aname,Aid) values(?,?)"; System.out.println(sql); st=conn.prepareStatement(sql); st.setString(1, name); st.setInt(2, id); st.addBatch(); st.setString(1, name+"ss"); st.setInt(2, id+15); st.addBatch(); st.executeBatch();
Transaction
Transaction我们一般翻译成会话,就是一个不可分割的多条(或一条)sql语句,在一个Transaction中,这些sql语句要么全部执行成功,要么一个也不执行。它有什么用?还用解释么?想想银行。
在jdbc中,默认一个sql语句就是一个transaction。
看看代码
try{ conn.setAutoCommit(false); st=conn.createStatement(); st.addBatch("insert into admininfo (Aname,Aid) values('"+name+"',"+id+") "); st.addBatch("insert into admininfo (Aname,Aid) values('"+name2+"',"+id2+") "); st.executeBatch(); conn.commit(); conn.setAutoCommit(true); //用完了得改回去 }catch(Exception e){ if(conn!=null){ conn.rollBack(); //sql代码撤销 conn.setAutoCommit(true); //还得改回去 } }
可滚动的结果集
String sql="select * from admininfo order by Aid"; st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); rs=st.executeQuery(sql); /* admininfo 表内容 * Aid Aname 15 dlf 16 董磊峰 18 董磊峰2 48 董磊峰2 49 董磊峰2 55 董磊峰2 154 董磊峰2 155 董磊峰2 487 董磊峰2 1599 董磊峰2ss 2000 董磊峰2 2015 董磊峰2ss 3000 董磊峰2666 8000 董磊峰2hhhh 10001 wyf 10002 zrk */ rs.absolute(4); System.out.println("第4 "+ rs.getInt("Aid")); System.out.println("第几条 "+ rs.getRow()); rs.first(); System.out.println("第一个 "+ rs.getInt("Aid")); rs.last(); System.out.println("最后一个 "+ rs.getInt("Aid")); System.out.println("总数 "+ rs.getRow()); System.out.println("是否最后一个 "+ rs.isLast()); System.out.println("最后结尾 "+ rs.isAfterLast()); rs.next(); System.out.println("最后结尾 "+ rs.isAfterLast());
第4 48
第几条 4
第一个 15
最后一个 10002
总数 16
是否最后一个 true
最后结尾 false
最后结尾 true
看看这些方法的名字还有结果,大家应该能知道方法的作用,不过isAfterLast方法大家估计有点迷惑。
最后一个的后面?
这个方法是判断当前指针是否已经到文件尾,注意:文件尾和最后一条记录是不同的。
比如我们开始读取 ResultSet 时,指针位于文件头,首先需要 rs.next() 执行这个方法,指针移到第一条记录后才可以进行读取。到文件尾也是一样的,读到最后一条记录后,再继续读就到文件尾了,没有记录了,执行 isAfterLast() 方法就返回 true 了。
参考资料
http://blog.163.com/yutao_inx_319/blog/static/207234007201311177482930/ java,ResultSet 类中的isAfterLast()方法
http://www.cnblogs.com/shosky/archive/2011/07/22/2114290.html 三种类加载方式的区别

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











No more need for pip? Come and learn how to uninstall pip effectively! Introduction: pip is one of Python's package management tools, which can easily install, upgrade and uninstall Python packages. However, sometimes we may need to uninstall pip, perhaps because we wish to use another package management tool, or because we need to completely clear the Python environment. This article will explain how to uninstall pip efficiently and provide specific code examples. 1. How to uninstall pip The following will introduce two common methods of uninstalling pip.

To learn more about the matplotlib color table, you need specific code examples 1. Introduction matplotlib is a powerful Python drawing library. It provides a rich set of drawing functions and tools that can be used to create various types of charts. The colormap (colormap) is an important concept in matplotlib, which determines the color scheme of the chart. In-depth study of the matplotlib color table will help us better master the drawing functions of matplotlib and make drawings more convenient.

Learn Pygame from scratch: complete installation and configuration tutorial, specific code examples required Introduction: Pygame is an open source game development library developed using the Python programming language. It provides a wealth of functions and tools, allowing developers to easily create a variety of type of game. This article will help you learn Pygame from scratch, and provide a complete installation and configuration tutorial, as well as specific code examples to get you started quickly. Part One: Installing Python and Pygame First, make sure you have

When editing text content in Word, you sometimes need to enter formula symbols. Some guys don’t know how to input the root number in Word, so Xiaomian asked me to share with my friends a tutorial on how to input the root number in Word. Hope it helps my friends. First, open the Word software on your computer, then open the file you want to edit, and move the cursor to the location where you need to insert the root sign, refer to the picture example below. 2. Select [Insert], and then select [Formula] in the symbol. As shown in the red circle in the picture below: 3. Then select [Insert New Formula] below. As shown in the red circle in the picture below: 4. Select [Radical Formula], and then select the appropriate root sign. As shown in the red circle in the picture below:

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Title: Learn the main function in Go language from scratch. As a simple and efficient programming language, Go language is favored by developers. In the Go language, the main function is an entry function, and every Go program must contain the main function as the entry point of the program. This article will introduce how to learn the main function in Go language from scratch and provide specific code examples. 1. First, we need to install the Go language development environment. You can go to the official website (https://golang.org

Learn pip installation from scratch and quickly master the skills. Specific code examples are required. Overview: pip is a Python package management tool that can easily install, upgrade and manage Python packages. For Python developers, it is very important to master the skills of using pip. This article will introduce the installation method of pip from scratch, and give some practical tips and specific code examples to help readers quickly master the use of pip. 1. Install pip Before using pip, you first need to install pip. pip

This website reported on August 23 that the Civil Aviation Administration of China and the National Development and Reform Commission jointly issued the "Guiding Opinions on Promoting the Construction of International Aviation Hubs" (hereinafter referred to as the "Guiding Opinions"). The "Guiding Opinions" make an overall plan for the construction of international aviation hubs, accelerate the construction of the "3+7+N" international aviation hub functional system from the aspects of functional positioning, planning and construction, coordinated operations, transportation services, etc., and have a clear understanding of the functions of international aviation hubs. Positioning has been refined and deepened. "3" refers to international aviation hubs such as Beijing, Shanghai, and Guangzhou. The three places are the frontier gateways for my country's opening up to the outside world. They will enhance their intercontinental connection capabilities and global radiation capabilities. In principle, long-distance international routes will be reasonably and orderly provided to Beijing, Shanghai, and Guangzhou. etc. Concentrate. "7" refers to Chengdu, Shenzhen, Chongqing, Kunming, Xi'an,
