Rumah >pangkalan data >tutorial mysql >Java进阶学习第十七天JDBC入门学习
文档版本 开发工具 测试平台 工程名字 日期 作者 备注 V1.0 2016.05.11 lutianfei none JDBC JDBC介绍 JDBC是什么? JDBC(Java Data Base Connectivity,java数据库连接) SUN公司为了简化、统一对数据库的操作,定义了一套Java操作数据库的规范,称之为JDBC。
文档版本 | 开发工具 | 测试平台 | 工程名字 | 日期 | 作者 | 备注 |
---|---|---|---|---|---|---|
V1.0 | 2016.05.11 | lutianfei | none |
Connection
Statement
ResultSet
PreparedStatement
CallableStatement
(它是用于调用存储过程)<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> <span class="hljs-keyword">user</span>( id <span class="hljs-keyword">int</span> <span class="hljs-keyword">primary</span> <span class="hljs-keyword">key</span> auto_increment, username <span class="hljs-keyword">varchar</span>(<span class="hljs-number">20</span>) <span class="hljs-keyword">unique</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">null</span>, password <span class="hljs-keyword">varchar</span>(<span class="hljs-number">20</span>) <span class="hljs-keyword">not</span> <span class="hljs-keyword">null</span>, email <span class="hljs-keyword">varchar</span>(<span class="hljs-number">40</span>) <span class="hljs-keyword">not</span> <span class="hljs-keyword">null</span> );</span> <span class="hljs-operator"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">USER</span> <span class="hljs-keyword">VALUES</span>(<span class="hljs-keyword">NULL</span>,<span class="hljs-string">'tom'</span>,<span class="hljs-string">'123'</span>,<span class="hljs-string">'tom@163.com'</span>);</span> <span class="hljs-operator"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> <span class="hljs-keyword">USER</span> <span class="hljs-keyword">VALUES</span>(<span class="hljs-keyword">NULL</span>,<span class="hljs-string">'fox'</span>,<span class="hljs-string">'123'</span>,<span class="hljs-string">'fox@163.com'</span>);</span></code>
<code class=" hljs avrasm">public static void main(String[] args) throws SQLException { // <span class="hljs-number">1.</span>注册驱动 // DriverManager<span class="hljs-preprocessor">.registerDriver</span>(new Driver())<span class="hljs-comment">; //加载了两个驱动</span> Class<span class="hljs-preprocessor">.forName</span>(<span class="hljs-string">"com.mysql.jdbc.Driver"</span>)<span class="hljs-comment">; // 加载mysql驱动</span> // <span class="hljs-number">2.</span>获取连接对象 Connection con = DriverManager<span class="hljs-preprocessor">.getConnection</span>( <span class="hljs-string">"jdbc:mysql://localhost:3306/day17"</span>, <span class="hljs-string">"root"</span>, <span class="hljs-string">"abc"</span>)<span class="hljs-comment">;</span> // <span class="hljs-number">3.</span>通过连接对象获取操作sql语句Statement Statement <span class="hljs-keyword">st</span> = con<span class="hljs-preprocessor">.createStatement</span>()<span class="hljs-comment">;</span> // <span class="hljs-number">4.</span>操作sql语句 String sql = <span class="hljs-string">"select * from user"</span><span class="hljs-comment">;</span> // 操作sql语句(select语句),会得到一个ResultSet结果集 ResultSet rs = <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.executeQuery</span>(sql)<span class="hljs-comment">;</span> // <span class="hljs-number">5.</span>遍历结果集 // boolean flag = rs<span class="hljs-preprocessor">.next</span>()<span class="hljs-comment">; // 向下移动,返回值为true,代表有下一条记录.</span> // int id = rs<span class="hljs-preprocessor">.getInt</span>(<span class="hljs-string">"id"</span>)<span class="hljs-comment">;</span> // String username=rs<span class="hljs-preprocessor">.getString</span>(<span class="hljs-string">"username"</span>)<span class="hljs-comment">;</span> // System<span class="hljs-preprocessor">.out</span><span class="hljs-preprocessor">.println</span>(id)<span class="hljs-comment">;</span> // System<span class="hljs-preprocessor">.out</span><span class="hljs-preprocessor">.println</span>(username)<span class="hljs-comment">;</span> while(rs<span class="hljs-preprocessor">.next</span>()){ int id=rs<span class="hljs-preprocessor">.getInt</span>(<span class="hljs-string">"id"</span>)<span class="hljs-comment">;</span> String username=rs<span class="hljs-preprocessor">.getString</span>(<span class="hljs-string">"username"</span>)<span class="hljs-comment">;</span> String password=rs<span class="hljs-preprocessor">.getString</span>(<span class="hljs-string">"password"</span>)<span class="hljs-comment">;</span> String email=rs<span class="hljs-preprocessor">.getString</span>(<span class="hljs-string">"email"</span>)<span class="hljs-comment">;</span> System<span class="hljs-preprocessor">.out</span><span class="hljs-preprocessor">.println</span>(id+<span class="hljs-string">" "</span>+username+<span class="hljs-string">" "</span>+password+<span class="hljs-string">" "</span>+email)<span class="hljs-comment">;</span> } //<span class="hljs-number">6.</span>释放资源 rs<span class="hljs-preprocessor">.close</span>()<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.close</span>()<span class="hljs-comment">;</span> con<span class="hljs-preprocessor">.close</span>()<span class="hljs-comment">;</span> } </code>
JDBC程序中的DriverManager
是java.sql
包下的一个驱动管理的工具类,可以理解成是一个容器(Vector),可以装入很多数据库驱动,并创建与数据库的链接,这个API的常用方法:
registDriver方法
分析
<code class=" hljs cs"><span class="hljs-keyword">static</span> { <span class="hljs-keyword">try</span> { java.sql.DriverManager.registerDriver(<span class="hljs-keyword">new</span> Driver()); } <span class="hljs-keyword">catch</span> (SQLException E) { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"Can't register driver!"</span>); } }</code>
上述代码的问题:
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConection(String url,String user,String password);
jdbc: mysql ://localhsot:3306/数据库名
jdbc : oracle :thin :@ localhost :1521 :sid
DriverManager作用总结:
URL用于标识数据库的位置,程序员通过URL地址告诉JDBC程序连接哪个数据库,URL的写法为:
jdbc : mysql : // localhost :3306/test ?key=value
url格式
jdbc : mysql ://localhost:3306/day17
mysql的url可以简写
jdbc : mysql : ///day17
在url后面可以带参数
java.sql.Connection
,它代表的是一个连接对象。简单说,就是我们程序与数据库连接。
Connection作用:
PreparedStatement对象
.创建向数据库发送预编译sql的PrepareSatement对象 CallableStatement
,创建执行存储过程的callableStatement对象。 java.sql.Statement
用于向数据库发送SQL语句,执行sql语句。1.执行SQL
insert
update
delete
select
2.批处理操作
java.sql.ResultSet
它是用于封装select语句执行后查询的结果。Resultset封装执行结果时,采用的类似于表格的方式。ResultSet 对象维护了一个指向表格数据行的游标cursor
,初始的时候,游标在第一行之前,调用ResultSet.next() 方法
,可以使游标指向具体的数据行,进而调用方法获取该行的数据。1.next()方法
2.可以通过ResultSet提供的getXxx()方法来获取当前游标指向的这条记录中的列数据。
如果列的类型不知道,可以通过下面的方法来操作
常用数据类型转换表
JDBC程序运行完后,切记要释放程序在运行过程中,创建的那些与数据库进行交互的对象,这些对象通常是ResultSet, Statement和Connection对象。
特别是Connection对象
,它是非常稀有的资源,用完后必须马上释放,如果Connection不能及时、正确的关闭,极易导致系统宕机。
为确保资源释放代码能运行,资源释放代码也一定要放在finally
语句中。
完整版JDBC示例代码:
<code class=" hljs cs"> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) { Connection con = <span class="hljs-keyword">null</span>; Statement st = <span class="hljs-keyword">null</span>; ResultSet rs = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { <span class="hljs-comment">// 1.注册驱动</span> Class.forName(<span class="hljs-string">"com.mysql.jdbc.Driver"</span>); <span class="hljs-comment">// 2.获取连接</span> con = DriverManager.getConnection(<span class="hljs-string">"jdbc:mysql:///day17"</span>, <span class="hljs-string">"root"</span>, <span class="hljs-string">"abc"</span>); <span class="hljs-comment">// 3.获取操作sql语句对象Statement</span> st = con.createStatement(); <span class="hljs-comment">// 4.执行sql</span> rs = st.executeQuery(<span class="hljs-string">"select * from user"</span>); <span class="hljs-comment">// 5.遍历结果集</span> <span class="hljs-keyword">while</span> (rs.next()) { <span class="hljs-keyword">int</span> id = rs.getInt(<span class="hljs-string">"id"</span>); String username = rs.getString(<span class="hljs-string">"username"</span>); String password = rs.getString(<span class="hljs-string">"password"</span>); String email = rs.getString(<span class="hljs-string">"email"</span>); System.<span class="hljs-keyword">out</span>.println(id + <span class="hljs-string">" "</span> + username + <span class="hljs-string">" "</span> + password + <span class="hljs-string">" "</span> + email); } } <span class="hljs-keyword">catch</span> (ClassNotFoundException e) { e.printStackTrace(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-comment">// 6.释放资源</span> <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (rs != <span class="hljs-keyword">null</span>) { rs.close(); } } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (st != <span class="hljs-keyword">null</span>) st.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (con != <span class="hljs-keyword">null</span>) con.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } } } }</code>
Jdbc中的statement对象用于向数据库发送SQL语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement对象的executeUpdate方法
,用于向数据库发送增、删、改的sql语句,executeUpdate执行完后,将会返回一个整数(即增删改语句导致了数据库几行数据发生了变化)。
Statement.executeQuery方法
用于向数据库发送查询语句,executeQuery方法返回代表查询结果的ResultSet对象。
1.查询
4.添加
练习:编写程序对User表进行增删改查操作。
<code class=" hljs java"><span class="hljs-comment">//jdbc.properties</span> driverClass=com.mysql.jdbc.Driver url=jdbc:mysql:<span class="hljs-comment">///day17</span> username=root password=abc <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JdbcUtils</span> {</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String DRIVERCLASS; <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String URL; <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String USERNAME; <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String PASSWORD; <span class="hljs-keyword">static</span> { DRIVERCLASS = ResourceBundle.getBundle(<span class="hljs-string">"jdbc"</span>).getString(<span class="hljs-string">"driverClass"</span>); URL = ResourceBundle.getBundle(<span class="hljs-string">"jdbc"</span>).getString(<span class="hljs-string">"url"</span>); USERNAME = ResourceBundle.getBundle(<span class="hljs-string">"jdbc"</span>).getString(<span class="hljs-string">"username"</span>); PASSWORD = ResourceBundle.getBundle(<span class="hljs-string">"jdbc"</span>).getString(<span class="hljs-string">"password"</span>); } <span class="hljs-keyword">static</span> { <span class="hljs-keyword">try</span> { <span class="hljs-comment">// 将加载驱动操作,放置在静态代码块中.这样就保证了只加载一次.</span> Class.forName(DRIVERCLASS); } <span class="hljs-keyword">catch</span> (ClassNotFoundException e) { e.printStackTrace(); } } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Connection <span class="hljs-title">getConnection</span>() <span class="hljs-keyword">throws</span> SQLException { <span class="hljs-comment">// 2.获取连接</span> Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD); <span class="hljs-keyword">return</span> con; } <span class="hljs-comment">//关闭操作</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">closeConnection</span>(Connection con) <span class="hljs-keyword">throws</span> SQLException{ <span class="hljs-keyword">if</span>(con!=<span class="hljs-keyword">null</span>){ con.close(); } } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">closeStatement</span>(Statement st) <span class="hljs-keyword">throws</span> SQLException{ <span class="hljs-keyword">if</span>(st!=<span class="hljs-keyword">null</span>){ st.close(); } } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">closeResultSet</span>(ResultSet rs) <span class="hljs-keyword">throws</span> SQLException{ <span class="hljs-keyword">if</span>(rs!=<span class="hljs-keyword">null</span>){ rs.close(); } } }</code>
<code class=" hljs cs"><span class="hljs-comment">//jdbc的crud操作</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> JdbcDemo6 { @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">findByIdTest</span>() { <span class="hljs-comment">// 1.定义sql</span> String sql = <span class="hljs-string">"select * from user where id=1"</span>; Connection con = <span class="hljs-keyword">null</span>; Statement st = <span class="hljs-keyword">null</span>; ResultSet rs = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { <span class="hljs-comment">// 1.注册驱动</span> Class.forName(<span class="hljs-string">"com.mysql.jdbc.Driver"</span>); <span class="hljs-comment">// 2.获取连接</span> con = DriverManager.getConnection(<span class="hljs-string">"jdbc:mysql:///day17"</span>, <span class="hljs-string">"root"</span>, <span class="hljs-string">"abc"</span>); <span class="hljs-comment">// 3.获取操作sql语句对象Statement</span> st = con.createStatement(); <span class="hljs-comment">// 4.执行sql</span> rs = st.executeQuery(sql); <span class="hljs-comment">// 5.遍历结果集</span> <span class="hljs-keyword">while</span> (rs.next()) { <span class="hljs-keyword">int</span> id = rs.getInt(<span class="hljs-string">"id"</span>); String username = rs.getString(<span class="hljs-string">"username"</span>); String password = rs.getString(<span class="hljs-string">"password"</span>); String email = rs.getString(<span class="hljs-string">"email"</span>); System.<span class="hljs-keyword">out</span>.println(id + <span class="hljs-string">" "</span> + username + <span class="hljs-string">" "</span> + password + <span class="hljs-string">" "</span> + email); } } <span class="hljs-keyword">catch</span> (ClassNotFoundException e) { e.printStackTrace(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-comment">// 6.释放资源</span> <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (rs != <span class="hljs-keyword">null</span>) { rs.close(); } } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (st != <span class="hljs-keyword">null</span>) st.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (con != <span class="hljs-keyword">null</span>) con.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } } } <span class="hljs-comment">// 添加操作</span> @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addTest</span>() { <span class="hljs-comment">// 定义sql</span> String sql = <span class="hljs-string">"insert into user values(null,'张三','123','zs@163.com')"</span>; Connection con = <span class="hljs-keyword">null</span>; Statement st = <span class="hljs-keyword">null</span>; ResultSet rs = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { <span class="hljs-comment">// 1.注册驱动</span> Class.forName(<span class="hljs-string">"com.mysql.jdbc.Driver"</span>); <span class="hljs-comment">// 2.获取连接</span> con = DriverManager.getConnection(<span class="hljs-string">"jdbc:mysql:///day17"</span>, <span class="hljs-string">"root"</span>, <span class="hljs-string">"abc"</span>); <span class="hljs-comment">// 3.获取操作sql语句对象Statement</span> st = con.createStatement(); <span class="hljs-comment">// 4.执行sql</span> <span class="hljs-keyword">int</span> row = st.executeUpdate(sql); <span class="hljs-keyword">if</span> (row != <span class="hljs-number">0</span>) { System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"添加成功"</span>); } } <span class="hljs-keyword">catch</span> (ClassNotFoundException e) { e.printStackTrace(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-comment">// 6.释放资源</span> <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (rs != <span class="hljs-keyword">null</span>) { rs.close(); } } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (st != <span class="hljs-keyword">null</span>) st.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (con != <span class="hljs-keyword">null</span>) con.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } } } <span class="hljs-comment">// update操作</span> @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateTest</span>() { <span class="hljs-comment">// 将id=3的人的password修改为456</span> String password = <span class="hljs-string">"456"</span>; String sql = <span class="hljs-string">"update user set password='"</span> + password + <span class="hljs-string">"' where id=3"</span>; <span class="hljs-comment">// 1.得到Connection</span> Connection con = <span class="hljs-keyword">null</span>; Statement st = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { con = JdbcUtils1.getConnection(); <span class="hljs-comment">// 3.获取操作sql语句对象Statement</span> st = con.createStatement(); <span class="hljs-comment">// 4.执行sql</span> <span class="hljs-keyword">int</span> row = st.executeUpdate(sql); <span class="hljs-keyword">if</span> (row != <span class="hljs-number">0</span>) { System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"修改成功"</span>); } } <span class="hljs-keyword">catch</span> (ClassNotFoundException e) { e.printStackTrace(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-comment">// 关闭资源</span> <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (st != <span class="hljs-keyword">null</span>) st.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">try</span> { <span class="hljs-keyword">if</span> (con != <span class="hljs-keyword">null</span>) con.close(); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } } } <span class="hljs-comment">// delete测试</span> @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTest</span>() { <span class="hljs-comment">// 将id=3的人删除</span> String sql = <span class="hljs-string">"delete from user where id=2"</span>; <span class="hljs-comment">// 1.得到Connection</span> Connection con = <span class="hljs-keyword">null</span>; Statement st = <span class="hljs-keyword">null</span>; <span class="hljs-keyword">try</span> { con = JdbcUtils.getConnection(); <span class="hljs-comment">// 3.获取操作sql语句对象Statement</span> st = con.createStatement(); <span class="hljs-comment">// 4.执行sql</span> <span class="hljs-keyword">int</span> row = st.executeUpdate(sql); <span class="hljs-keyword">if</span> (row != <span class="hljs-number">0</span>) { System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"删除成功"</span>); } } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } <span class="hljs-keyword">finally</span> { <span class="hljs-comment">// 关闭资源</span> <span class="hljs-keyword">try</span> { JdbcUtils.closeStatement(st); JdbcUtils.closeConnection(con); } <span class="hljs-keyword">catch</span> (SQLException e) { e.printStackTrace(); } } } }</code>
默认得到的ResultSet它只能向下遍历(next()),对于ResultSet它可以设置成是滚动的,可以向上遍历,或者直接定位到一个指定的物理行号。
设置滚动结果集的方法
createStatement()
;而使用带参数的createStatement(int,int)
<code class=" hljs java">Statement createStatement(<span class="hljs-keyword">int</span> resultSetType, <span class="hljs-keyword">int</span> resultSetConcurrency) <span class="hljs-keyword">throws</span> SQLException 、 Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);</code>
第一个参数值, resultSetType
第二个参数值,resultSetConcurrency
以上五个值,可以有三种搭配方式
常用API
DAO模式
(Data Access Object 数据访问对象):在持久层通过DAO将数据源操作完全封装起来,业务层通过操作Java对象,完成对数据源操作需求:
1.web层
具体代码见工程day17_2
。
用户注册流程
xxx’ or ‘1’=‘1
2、对于防范 SQL 注入,可以采用PreparedStatement
取代Statement
。
Connection.preparedStatement(sql)
方法获得PreparedStatement使用总结
?
占位 ?
“的序号.注意:从1开始。关于PreparedStatement优点:
在实际开发中,程序需要把大文本 Text
或二进制数据 Blob
保存到数据库。
Text
是mysql叫法,Oracle中叫Clob
大数据
也称之为LOB
(Large Objects),LOB又分为:
Text和blob分别又分为:
对于大数据操作,我们一般只有两种: insert select
演示1: 大二进制操作
<code class=" hljs sql"><span class="hljs-operator"><span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> myblob( id <span class="hljs-keyword">int</span> <span class="hljs-keyword">primary</span> <span class="hljs-keyword">key</span> auto_increment, content longblob )</span></code>
<code class=" hljs cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> MyBlobTest { <span class="hljs-comment">// 添加</span> @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save</span>() throws SQLException, IOException { String sql = <span class="hljs-string">"insert into myblob values(null,?)"</span>; <span class="hljs-comment">// 1.获取Connection</span> Connection con = JdbcUtils.getConnection(); <span class="hljs-comment">// 2.获取PreparedStatement</span> PreparedStatement pst = con.prepareStatement(sql); <span class="hljs-comment">// 3.插入值</span> File file = <span class="hljs-keyword">new</span> File(<span class="hljs-string">"D:\\java1110\\day17-jdbc\\视频\\3.jdbc快速入门.avi"</span>); FileInputStream fis = <span class="hljs-keyword">new</span> FileInputStream(file); pst.setBinaryStream(<span class="hljs-number">1</span>, fis, (<span class="hljs-keyword">int</span>) (file.length())); <span class="hljs-comment">//MySQL驱动只支持最后一个参数为int类型的方法</span> <span class="hljs-keyword">int</span> row = pst.executeUpdate(); <span class="hljs-keyword">if</span> (row != <span class="hljs-number">0</span>) { System.<span class="hljs-keyword">out</span>.println(<span class="hljs-string">"插入成功"</span>); } <span class="hljs-comment">// 4.释放资源</span> fis.close(); pst.close(); con.close(); } <span class="hljs-comment">// 获取</span> @Test <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">get</span>() throws SQLException, IOException { String sql = <span class="hljs-string">"select * from myblob where id=?"</span>; <span class="hljs-comment">// 1.获取Connection</span> Connection con = JdbcUtils.getConnection(); <span class="hljs-comment">// 2.获取PreparedStatement</span> PreparedStatement pst = con.prepareStatement(sql); pst.setInt(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>); <span class="hljs-comment">// 3.得到结果集</span> ResultSet rs = pst.executeQuery(); <span class="hljs-comment">// 4.遍历结果集</span> <span class="hljs-keyword">if</span> (rs.next()) { <span class="hljs-comment">// System.out.println(rs.getInt("id"));</span> InputStream <span class="hljs-keyword">is</span> = rs.getBinaryStream(<span class="hljs-string">"content"</span>);<span class="hljs-comment">// 得到的这个输入流它的源可以理解成就是数据库中的大二进制信息</span> FileOutputStream fos = <span class="hljs-keyword">new</span> FileOutputStream(<span class="hljs-string">"d:/a.avi"</span>); <span class="hljs-keyword">int</span> len = -<span class="hljs-number">1</span>; <span class="hljs-keyword">byte</span>[] b = <span class="hljs-keyword">new</span> <span class="hljs-keyword">byte</span>[<span class="hljs-number">1024</span> * <span class="hljs-number">100</span>]; <span class="hljs-keyword">while</span> ((len = <span class="hljs-keyword">is</span>.read(b)) != -<span class="hljs-number">1</span>) { fos.write(b, <span class="hljs-number">0</span>, len); fos.flush(); } fos.close(); <span class="hljs-keyword">is</span>.close(); } <span class="hljs-comment">// 5.关闭</span> rs.close(); pst.close(); con.close(); } }</code>
向表中插入数据可能出现的问题
问题1:java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBinaryStream(ILjava/io/InputStream;)
原因:mysql驱动不支持setBinaryStream(int,InputStream);
修改成 pst.setBinaryStream(1, fis,file.length());
原因:因为mysql驱动不支 setBinaryStream(int,InputStream,long);
解决: mysql驱动支持setBinaryStream(int,InputStream,int);
注意:如果文件比较大,那么需要在my.ini文件中配置
总结:
设置
:<code class=" hljs perl">PreparedStatement.setCharacterStream(<span class="hljs-keyword">index</span>, reader, <span class="hljs-keyword">length</span>); <span class="hljs-regexp">//</span>注意<span class="hljs-keyword">length</span>长度须设置,并且设置为<span class="hljs-keyword">int</span>型 //当包过大时修改配置:[mysqld] max_allowed_packet=<span class="hljs-number">64</span>M</code>
获取
:<code class=" hljs avrasm">reader = resultSet. getCharacterStream(i)<span class="hljs-comment">;</span> 等价于 reader = resultSet<span class="hljs-preprocessor">.getClob</span>(i)<span class="hljs-preprocessor">.getCharacterStream</span>()<span class="hljs-comment">;</span></code>
<code class=" hljs vhdl">create table mytext( id int primary key auto_increment, content longtext ) //存储 <span class="hljs-keyword">File</span> <span class="hljs-keyword">file</span> = <span class="hljs-keyword">new</span> <span class="hljs-keyword">File</span>(<span class="hljs-string">"D:\\java1110\\workspace\\day17_3\\a.txt"</span>); FileReader fr = <span class="hljs-keyword">new</span> FileReader(<span class="hljs-keyword">file</span>); pst.setCharacterStream(<span class="hljs-number">1</span>, fr, (int) (<span class="hljs-keyword">file</span>.length())); //获取: Reader r = rs.getCharacterStream(<span class="hljs-string">"content"</span>); </code>
设置
: PreparedStatement. setBinaryStream(i, inputStream, length);
获取
: InputStream in = resultSet.getBinaryStream(i);
InputStream in = resultSet.getBlob(i).getBinaryStream();
<code class=" hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTextTest</span> {</span> <span class="hljs-comment">// 存储</span> <span class="hljs-annotation">@Test</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save</span>() <span class="hljs-keyword">throws</span> SQLException, FileNotFoundException { String sql = <span class="hljs-string">"insert into mytext values(null,?)"</span>; <span class="hljs-comment">// 1.获取Connection</span> Connection con = JdbcUtils.getConnection(); <span class="hljs-comment">// 2.获取PreparedStatement</span> PreparedStatement pst = con.prepareStatement(sql); <span class="hljs-comment">// 3.插入值</span> File file = <span class="hljs-keyword">new</span> File(<span class="hljs-string">"D:\\java1110\\workspace\\day17_3\\a.txt"</span>); FileReader fr = <span class="hljs-keyword">new</span> FileReader(file); pst.setCharacterStream(<span class="hljs-number">1</span>, fr, (<span class="hljs-keyword">int</span>) (file.length())); pst.executeUpdate(); <span class="hljs-comment">// 4.释放资源</span> pst.close(); con.close(); } <span class="hljs-comment">// 获取</span> <span class="hljs-annotation">@Test</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">get</span>() <span class="hljs-keyword">throws</span> SQLException, IOException { String sql = <span class="hljs-string">"select * from mytext where id=?"</span>; <span class="hljs-comment">// 1.获取Connection</span> Connection con = JdbcUtils.getConnection(); <span class="hljs-comment">// 2.获取PreparedStatement</span> PreparedStatement pst = con.prepareStatement(sql); pst.setInt(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>); <span class="hljs-comment">// 3.得到结果集</span> ResultSet rs = pst.executeQuery(); <span class="hljs-comment">// 4.遍历结果集</span> <span class="hljs-keyword">if</span> (rs.next()) { Reader r = rs.getCharacterStream(<span class="hljs-string">"content"</span>); FileWriter fw = <span class="hljs-keyword">new</span> FileWriter(<span class="hljs-string">"d:/笔记.txt"</span>); <span class="hljs-keyword">int</span> len = -<span class="hljs-number">1</span>; <span class="hljs-keyword">char</span>[] ch = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">1024</span> * <span class="hljs-number">100</span>]; <span class="hljs-keyword">while</span> ((len = r.read(ch)) != -<span class="hljs-number">1</span>) { fw.write(ch, <span class="hljs-number">0</span>, len); fw.flush(); } fw.close(); r.close(); } pst.close(); con.close(); } }</code>
业务场景:当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
实现批处理有两种方式,第一种方式:
采用Statement.addBatch(sql)方式实现批处理:
实现批处理的第二种方式
采用PreparedStatement.addBatch()实现批处理
两个对象执行批处理区别?
<code class=" hljs sql">Connection conn = null; Statement st = null; ResultSet rs = null; try { conn = JdbcUtil.getConnection(); String sql1 = "<span class="hljs-operator"><span class="hljs-keyword">insert</span> <span class="hljs-keyword">into</span> person(name,password,email,birthday) <span class="hljs-keyword">values</span>(<span class="hljs-string">'kkk'</span>,<span class="hljs-string">'123'</span>,<span class="hljs-string">'abc@sina.com'</span>,<span class="hljs-string">'1978-08-08'</span>)<span class="hljs-string">"; String sql2 = "</span><span class="hljs-keyword">update</span> <span class="hljs-keyword">user</span> <span class="hljs-keyword">set</span> password=<span class="hljs-string">'123456'</span> <span class="hljs-keyword">where</span> id=<span class="hljs-number">3</span><span class="hljs-string">"; st = conn.createStatement(); st.addBatch(sql1); //把SQL语句加入到批命令中 st.addBatch(sql2); //把SQL语句加入到批命令中 st.executeBatch(); } finally{ JdbcUtil.free(conn, st, rs); }</span></span></code>
<code class=" hljs avrasm">conn = JdbcUtil<span class="hljs-preprocessor">.getConnection</span>()<span class="hljs-comment">;</span> String sql = <span class="hljs-string">"insert into person(name,password,email,birthday) values(?,?,?,?)"</span><span class="hljs-comment">;</span> <span class="hljs-keyword">st</span> = conn<span class="hljs-preprocessor">.prepareStatement</span>(sql)<span class="hljs-comment">;</span> for(int i=<span class="hljs-number">0</span><span class="hljs-comment">;i<50000;i++){</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.setString</span>(<span class="hljs-number">1</span>, <span class="hljs-string">"aaa"</span> + i)<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.setString</span>(<span class="hljs-number">2</span>, <span class="hljs-string">"123"</span> + i)<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.setString</span>(<span class="hljs-number">3</span>, <span class="hljs-string">"aaa"</span> + i + <span class="hljs-string">"@sina.com"</span>)<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.setDate</span>(<span class="hljs-number">4</span>,new Date(<span class="hljs-number">1980</span>, <span class="hljs-number">10</span>, <span class="hljs-number">10</span>))<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.addBatch</span>()<span class="hljs-comment">; </span> if(i%<span class="hljs-number">1000</span>==<span class="hljs-number">0</span>){ <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.executeBatch</span>()<span class="hljs-comment">;</span> <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.clearBatch</span>()<span class="hljs-comment">;</span> } } <span class="hljs-keyword">st</span><span class="hljs-preprocessor">.executeBatch</span>()<span class="hljs-comment">;</span> </code>
useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true
采用dao模式 使用PreparedStatement操作
2.使用PreparedStatement完成CRUD
客户信息表DAO编写