(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 driver
try {//加载驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//create connection
try {//建立连接
conn=DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create Statement
try {//建立statement
st=conn.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//execute query执行查询
public ResultSet executeQuery(String sql)
{
if(st==null)
{
initDB();
}
try {
rs=st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.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 ResultSet
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null)//类似rs
{ //close Statement
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//close connection
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
(1)executeQuery只能执行SELECT语句;
(2)executeUpdate可以执行DML语句;
(3)Statement里只有一个ResultSet,每执行一次executeQuery()就会new一次ResultSet!
因此若执行两次executeQuery();第一次执行的结果集会被冲掉!