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.CreateStatment() //首先获取语句对象
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
Class.forName(“XX.XX”)的含义
Class.forName(xxx.xx.xx) 返回的是一个类,.newInstance() 后才创建一个对象
Class.forName(xxx.xx.xx)的作用是要求JVM查找并加载指定的类,
也就是说JVM会执行该类的静态代码段
在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,
即任何一个JDBC Driver的Driver类的代码都必须类似如下:
public class MyJDBCDriver implements Driver {
static {
DriverManager.registerDriver(new MyJDBCDriver());
}
}
所以我们在使用JDBC时只需要Class.forName(XXX.XXX)就可以了
例子:访问mysql数据库
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCExample{
public static void main(String[] args) throws Exception{
//加载驱动程序 向DriverManager注册
Class.forName("com.mysql.jdbc.Driver");
//连接数据库 获取Connection类的对象
String url = "jdbc:mysql://127.0.0.1/数据库名";
Connection conn = DriverManager.getConnection(url,"用户名","密码");
//创建语句对象