java的JDBC简单案例
Driver接口
Driver是每个驱动程序类必须实现的接口,专门提供给数据厂商使用
在编写JDBC程序时,必须要把所使用的数据库驱动程序和类库
(指MySQL的驱动JAR包)加载到项目的classpath中。
解压后添加到项目中
根据代码提示加载Driver的包
Class.forName("com.mysql.jdbc.Driver");
Connection接口
Connection接口用于创建数据库的连接,只有获得该连接对象后才可以访问数据库,并操作数据表。
String url = "jdbc:mysql://127.0.0.1:3306/xiaoxiaoran";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
Statement接口
利用该对象把普通的SQL语句发送到数据库进行编译,然后返回数据库的处理结果。
PreparedStatement接口
PreparedStatement是Statement的子接口,拥有Statement接口的所有方法,并且可以对SQL语句进行预编译,预编译后的数据会存储在PreparedStatement对象中
PreparedStatement接口还扩展了带有参数SQL语句的执行操作,应用于该接口中的SQL语句可以使用占位符“?”代替其参数,然后通过setXxx()方法为SQL语句的参数赋值
sql = "select * from books where bId>? ";
PreparedStatement ptmt = conn.prepareStatement(sql);
ptmt.setInt(1, 40);
rs = ptmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "-此书作者-->" + rs.getString("author"));
}
rs.close();
sql = "UPDATE books SET bName=? WHERE bid =? ";
PreparedStatement ptmt2 = conn.prepareStatement(sql);
ptmt2.setString(1, "xiaoxiaoran");
ptmt2.setInt(2, 45);
ptmt2.execute();
ResultSet接口
ResultSet接口用于保存JDBC执行查询时返回的结果集,该结果集与数据库表字段相对应。
在应用程序中经常使用next()方法作为while循环的条件以迭代ResultSet结果集
String sql = "select * from books where bId>40 ";
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "-此书作者-->" + rs.getString("author"));
}
rs.close();
案例代码
案例数据库表结构
import java.sql.*;
public class Sql {
public static void main(String[] args) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/xiaoxiaoran";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
String sql = "select * from books where bId>40 ";
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "-此书作者-->" + rs.getString("author"));
}
rs.close();
sql = "select * from books where bId>? ";
PreparedStatement ptmt = conn.prepareStatement(sql);
ptmt.setInt(1, 40);
rs = ptmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "-此书作者-->" + rs.getString("author"));
}
rs.close();
sql = "UPDATE books SET bName=? WHERE bid =? ";
PreparedStatement ptmt2 = conn.prepareStatement(sql);
ptmt2.setString(1, "xiaoxiaoran");
ptmt2.setInt(2, 45);
ptmt2.execute();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (rs != null)
rs.close();
rs = null;
stmt.close();
stmt = null;
conn.close();
conn = null;
}
}
}