构建JDBC程序操作数据库包括6个步骤:
1. 引入相关jar包(包括mysql等的驱动包)
2. 注册JDBC驱动
3. 通过DriverManager打开连接
4. 执行SQL操作
5. 从SQL操作结果集中提取数据
6. 清理环境,也就是关闭连接
下面是简单的示例
package jdbc.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestJDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://url:3306/mysql";
//Database credentials
static final String USERNAME = "root";
static final String PASSWORD = "123456";
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
//Register JDBC Driver
Class.forName(JDBC_DRIVER);
//Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
//Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "select id, name from test1";
ResultSet rs = stmt.executeQuery(sql);
//Extract data from result set
while(rs.next()){
//Retrive by column name
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id);
System.out.println("NAME: " + name);
}
//Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
//finally block used to close resource
try{
if(stmt != null){
stmt.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn != null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
System.out.println("--------END--------");
}
}