最近学习jsp,从最基础的学起,首先先讲讲JDBC,下面是JDBC编程步骤:
1.Load the Driver
(1)Class.forName() / Class.forName().newInstance() / new DriverName()
(2)实例化时自动向DriverManager注册,不需显式调用DriverManager.registerDriver方法
2.Connect to the DataBase
(1)DriverManager.getConnection()
3.Execute the SQL
(1)Connection.CreateStatement()
(2)Statement.executeQuery()
(3)Statement.executeUpdate()
4.Retrieve the result data
(1)循环取得结果while(rs.next())
5.Show the result data
(1)将数据库中的各种类型转换为java中类型(getXXX)方法
6.Close
(1)close the ResultSet/close the Statement /close the Connection
自己编写了一个静态类,这样的话,做项目或者开发程序会比较方便、简单。这个连接是关于MySQL,其他的数据库都差不多,仅仅是把驱动的连接改变一下而已。
import java.sql.*;
public class DB {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/bbs", "root", "root"); //数据库连接,分别表示数据库、用户名、密码
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static Statement createStmt(Connection conn) {
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public static int executeUpdate(Connection conn, String sql) {
Statement stmt = null;
int ret=0;
try {
stmt=conn.createStatement();
ret=stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ret;
}
public static ResultSet executeQuery(Statement stmt, String sql) {
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public static void close(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void close(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static PreparedStatement prepareStmt(Connection conn,String sql,int autoGenerateKeys){
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql,autoGenerateKeys);
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}
public static PreparedStatement prepareStmt(Connection conn,String sql){
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}
}