JDBC驱动程序是Java程序和数据库之间的转换层,数据库驱动程序负责将JDBC调用成特定的数据库。
JDBC操作数据库的步骤如下:
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tech2", "root", "");
ps = conn.prepareStatement("select id,name,code,age,sex from t_student");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("name:" + name + "\tage:" + age);
}
} catch (ClassNotFoundException e) {
System.out.println("驱动加载失败");
} catch (SQLException e) {
System.out.println("查询对象创建失败");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != ps) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
在查询对象中,可以使用Statement和PreparedStatement,但是一般都使用预处理的PreparedStatement,一方面可以通过参数设置提供代码的质量,另一方面在进行数量级加大的查询或更新操作时,PreparedStatement效率更高。