JDBC(Java Database Connectivity)是一种Java API(应用程式介面),用于与关联式资料库系统进行交互。 它定义了一组Java 类和介面,使开发人员可以编写Java应用程式,以便通过标准SQL语言与各种RDBMS进行通信。
下面是一个简单的JDBC例子,使用JDBC API与MySQL数据库进行交互:
import java.sql.*;
public class JDBCTest {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sample_db";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM employees";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2) {
}
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
}
}
简要解释:
Class.forName()
DriverManager.getConnection()
连接到数据库Connection.createStatement()
创建一个 Statement
对象,并使用它来执行SQL查询ResultSet
对像来处理查询结果String sql = "SELECT * FROM myTable WHERE datetime > ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setTimestamp(1, new Timestamp(date.getTime()));
其中,conn是已经建立好的数据库连接对象,date是特定的日期对象。
String sql = "UPDATE myTable SET name = ?, age = ? WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 0; i < data.size(); i++) { //data为需要更新的数据
pstmt.setString(1, data.getName(i));
pstmt.setInt(2, data.getAge(i));
pstmt.setInt(3, data.getId(i));
pstmt.addBatch();
}
int[] result = pstmt.executeBatch();
其中,conn是已经建立好的数据库连接对象。
String sql = "SELECT * FROM myTable LIMIT ? OFFSET ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pageSize);
pstmt.setInt(2, (pageNum - 1) * pageSize);
其中,pageSize表示每页显示的记录数量,pageNum表示要查询的页码。
Connection conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
try {
Statement stmt = conn.createStatement();
// some sql operations here
stmt.execute("INSERT INTO myTable(name, age) VALUES('Tom', 20)");
stmt.execute("UPDATE myTable SET age = 22 WHERE name = 'Tom'");
conn.commit();
} catch (SQLException e) {
conn.rollback();
} finally {
conn.setAutoCommit(true);
conn.close();
}
String sql = "SELECT t1.*, t2.age FROM table1 t1 JOIN table2 t2 ON t1.id = t2.table1Id";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age1 = rs.getInt("age1");
int age2 = rs.getInt("age2");
System.out.println(name + ", " + age1 + ", " + age2);
}
其中,t1和t2分别代表要关联的两张表,table1Id是t1这张表中用来关联的id栏位名称。