关键语句(或关键词):
加载驱动程序:
Class.forName("oracle.jdbc.driver.OracleDriver");
通过调用jdk中的类方法forname来实现对jdbc包的调用
加载连接:
Connection conn= DriverManager.getConnection(ulr,user,password);
对connection接口的实现来获取对数据库的访问
对sql语句的引用(实现):
Statement statement=conn.createStatement();
利用Statement 来对字符串中的sql语句进行转换
int a=statement.executeUpdate(sql);
更新数据的操作:增、删、改 均调用statement 下的方法:executeUpdate()
查询语句则使用方法:executeQuery()
参数灵活传入
利用PreparedStatement 来实现
String sql="insert into regions(region_id,region_name) values(?,?)";
PreparedStatement preparedStatement=conn.prepareStatement(sql);
问号代表了可能会改变的参数
程序块
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("驱动加载成功");
//加载连接
String ulr="jdbc:oracle:thin:@localhost:1521:xe";
String user="hr";
String password="123";
Connection conn= DriverManager.getConnection(ulr,user,password);
System.out.println("连接成功");
String sql="select * from employees";
ResultSet rs=statement.executeQuery(sql);
rs.next();
System.out.println(rs.getString("first_name"));
System.out.println(rs.getString(2)+"\t"+rs.getString(3));//显示全名
//查询语句的拼接
String regionName="中国";
Integer regionId=8;
String sql="insert into regions(region_id,region_name) values("+regionId+",'"+regionName+"')";
System.out.println(sql);
int a=statement.executeUpdate(sql);
System.out.println(a);
//通过预编译来实现sql语句的灵活配置
String sql="insert into regions(region_id,region_name) values(?,?)";
PreparedStatement preparedStatement=conn.prepareStatement(sql);
String regionName="云南";
Integer region_id=6;
preparedStatement.setInt(1,region_id);
preparedStatement.setString(2,regionName);
preparedStatement.executeUpdate();
while (rs.next()){
System.out.println(rs.getString(2)+"\t"+rs.getString(3));
}
实例:
public static void main(String[] args) {
try {
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("驱动加载成功");
//加载连接
String ulr="jdbc:oracle:thin:@localhost:1521:xe";
String user="hr";
String password="123";
Connection conn= DriverManager.getConnection(ulr,user,password);
System.out.println("连接成功");
Statement statement=conn.createStatement();
String sql="select * from regions";
ResultSet rs=statement.executeQuery(sql);
List<Regions> regions=new ArrayList<>();
while (rs.next()){
Regions r=new Regions();
r.setRegion_id(rs.getInt("region_id"));
r.setRegion_name(rs.getString("region_name"));
regions.add(r);
//regions.add(new Regions(rs.getInt(1),rs.getString(2)));
}
rs.close();
for(Regions r:regions){
System.out.println(r);
}
功能实现:
查询信息
网友评论