使用JDBC访问数据库的过程
与数据库建立连接
如何与数据库建立连接呢?(注:这里以mysql为例)
(1)加载数据库驱动(通常使用Class类的forName()静态方法来加载驱动)
Class.forName("com.mysql.jdbc.Driver");
(2)通过DriverManager获取数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","数据库密码");
访问数据库
建立连接之后,就可以对数据库进行增删改查等操作。在JDBC中,数据库操作由Statement,PreParedStatement,
CallableStatement对象完成。
(一)Statement
(3)通过Connection对象创建Statement对象
Statement statement = connection.createStatement();
(4)使用Statement执行SQL语句
ResultSet resultSet = statement.executeQuery("select * from t1");
(二)PreParedStatement
(3)创建一个PreparedStatement对象
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM t1 WHERE cate_id=?");
(4)先为参数赋值,再使用executeQuery或executeUpdate方法执行
pstmt.setInt(1,3);
ResultSet rs1=pstmt.executeQuery();
(5)操作结果集
关闭连接
连接使用完毕,调用close()方法关闭连接。
使用Statement操作代码
import java.sql.*;
public class Test {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","111111");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from t1");
while (resultSet.next()){
System.out.println(resultSet.getInt("id")+" "+resultSet.getString("name"));
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用PreparedStatement操作代码
import java.sql.*;
public class Test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","111111");
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM t1 WHERE cate_id=?");
pstmt.setInt(1,3);
ResultSet rs1=pstmt.executeQuery();
while(rs1.next())
System.out.println("名称:"+rs1.getString("cate_name"));
pstmt.setInt(1,5);
ResultSet rs2=pstmt.executeQuery();
while(rs2.next())
System.out.println("名称:"+rs2.getString("cate_name"));
rs1.close();
rs2.close();
pstmt.close();
conn.close();
}
}