1.建立连接:
Class.forName = ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASSWD);
2.进行交互:
JDBC Statement, CallableStatement 和 PreparedStatement 接口定义的方法和属性,使可以发送SQL或PL/SQL命令和从数据库接收数据。
2.1 Statement
创建对象
Statement stmt = null;
try {
stmt = conn.createStatement( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
boolean execute(String SQL) : 如果ResultSet对象可以被检索返回布尔值true,否则返回false。使用这个方法来执行SQL DDL语句,或当需要使用真正的动态SQL。
int executeUpdate(String SQL) : 返回受影响的SQL语句执行的行的数目。使用此方法来执行,而希望得到一些受影响的行的SQL语句 - 例如,INSERT,UPDATE或DELETE语句。
ResultSet executeQuery(String SQL) : 返回ResultSet对象。当希望得到一个结果集使用此方法,就像使用一个SELECT语句。
2.2 PreparedStatement
创建对象
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
执行
String sql = "UPDATE Employees set age=? WHERE id=?";
stmt = conn.prepareStatement(sql);
//Bind values into the parameters.
stmt.setInt(1, 35); // This would set age
stmt.setInt(2, 102); // This would set ID
// Let us update age of the record with ID = 102;
int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
// Let us select all the records and display them.
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}