JDBC学习笔记(2)之statement

来源:互联网 发布:linux用户账号新建 编辑:程序博客网 时间:2024/05/16 11:17
(1)加载驱动;
(2) 建立连接;
(3)创建statement;
(4)执行查询;
(5)遍历结果集;
(6)关闭结果集;
(7)关闭statement;
(8)关闭连接;
statement下的executeQuery()只能执行select语句;
package jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class Encap {private static String url="jdbc:mysql://127.0.0.1:3306/***";private static String user="***";private static String password="***";private static Connection conn=null;private static Statement st=null;private static ResultSet rs=null;private static void initDB(){//load drivertry {//加载驱动Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}//create connectiontry {//建立连接conn=DriverManager.getConnection(url, user, password);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}//create Statementtry {//建立statementst=conn.createStatement();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}    //execute query执行查询public ResultSet executeQuery(String sql){if(st==null){initDB();}try {rs=st.executeQuery(sql);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return rs;}
<span style="white-space:pre">public static int executeUpdate(String sql)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>int res = 0;<span style="white-space:pre"></span>if(st==null)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>initDB();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>try {<span style="white-space:pre"></span>res=st.executeUpdate(sql);<span style="white-space:pre"></span>} catch (SQLException e) {<span style="white-space:pre"></span>// TODO Auto-generated catch block<span style="white-space:pre"></span>e.printStackTrace();<span style="white-space:pre"></span>}<span style="white-space:pre"></span>return res;<span style="white-space:pre"></span>}</span>
public static void close(){//关闭结果集,statement,连接if(rs!=null)//若rs==null,执行rs.close()会出错!{   //close ResultSettry {rs.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(st!=null)//类似rs{   //close Statementtry {st.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//close connectiontry {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


(1)executeQuery只能执行SELECT语句;

(2)executeUpdate可以执行DML语句;

(3)Statement里只有一个ResultSet,每执行一次executeQuery()就会new一次ResultSet!

  因此若执行两次executeQuery();第一次执行的结果集会被冲掉!



0 0
原创粉丝点击