JDBC

2016-07-04  本文已影响27人  738bc070cd74

JDBC 表示java的数据库连接,提供一套完整的访问数据库的接口。JDBC由两层体系构成

jdbc.png

JDBC组件

JDBC API提供了以下接口和类:

boolean execute(String SQL) : 返回一个布尔值true,如果ResultSet对象可以被检索,否则返回false。使用这个方法来执行SQL DDL语句,或当需要使用真正的动态SQL。
int executeUpdate(String SQL) : 返回受影响的SQL语句执行的行数。使用此方法来执行,而希望得到一些受影响的行的SQL语句 - 例如,INSERT,UPDATE或DELETE语句。
ResultSet executeQuery(String SQL) :返回ResultSet对象。当希望得到一个结果集使用此方法,就像使用一个SELECT语句。

加载驱动

Class.forName("com.mysql.jdbc.Driver");

建立连接

Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.33.10:3306/tbl_user", "root", "root");

创建声明

// 静态 SQL statement
Statement stmt = conn.createStatement();
// 动态SQL
PreparedStatement
// 存储过程
CallableStatement

执行操作

ResultSet rs = stmt.executeQuery("select * from user");

处理结果

while (rs.next()) {
    System.out.print(rs.getString("name"));
}

关闭连接

rs.close();
stmt.close();
conn.close();

操作记录

private static void createTable(Connection conn) throws SQLException {
String sql = "CREATE TABLE tb_user " +
        "(id INTEGER not NULL, " +
        " name VARCHAR(255), " +
        " pass VARCHAR(255), " +
        " age INTEGER, " +
        " PRIMARY KEY ( id ))";
Statement s = conn.createStatement();
s.executeUpdate(sql);
System.out.print("create table success");
s.close();}

private static void insertData(Connection conn) throws SQLException {
String sql = "insert into tb_user " +
        "values(1000, 'huben', '123456', 25)";
Statement s = conn.createStatement();
s.executeUpdate(sql);
s.close();}

private static void getData(Connection conn) throws SQLException {
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from tb_user");
while (rs.next()) {
    System.out.print(rs.getString("name")+":" + rs.getString("pass") +":"+ rs.getInt("age"));
}}

private static void update(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement("update tb_user set name = ?, pass = ?, age = ? where id = ?");
ps.setObject(1, "zhangsan");
ps.setObject(2, "654321");
ps.setObject(3, 20);
ps.setInt(4, 1000);
ps.executeUpdate();}
private static void delete(Connection conn) throws SQLException {
PreparedStatement ps = conn.prepareStatement("delete from tb_user where id = ?");
ps.setInt(1, 1000);
ps.executeUpdate();}
上一篇 下一篇

猜你喜欢

热点阅读