Java JDBC基本用法
准备oracle驱动包:maven添加oracle jdbc依赖
pom.xml
- <!-- oracle jdbc驱动 -->
- <dependency>
- <groupId>com.oracle</groupId>
- <artifactId>ojdbc5</artifactId>
- <version>11.2.0.1.0</version>
- <scope>runtime</scope>
- </dependency>
测试数据库表:
- create table TEST
- (
- username VARCHAR2(32) not null,
- password VARCHAR2(32)
- )
- insert into TEST (USERNAME, PASSWORD)
- values ('Obama', '1234');
- insert into TEST (USERNAME, PASSWORD)
- values ('John', '1234');
- insert into TEST (USERNAME, PASSWORD)
- values ('Mike', '1234');
- insert into TEST (USERNAME, PASSWORD)
- values ('Jim', '1234');
- insert into TEST (USERNAME, PASSWORD)
- values ('Ana', '1234');
- insert into TEST (USERNAME, PASSWORD)
- values ('Ennerson', '1234');
- commit;
示例Demo:
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- public class JDBC {
- public static void main(String[] args) throws SQLException {
- Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();//加载驱动类
- Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.168.100:1521/orcl","your_username", "your_password");
- try {
- System.out.println("======遍历TEST表所有的数据======");
- String sql = "select username,password from TEST ";
- PreparedStatement ps = conn.prepareStatement(sql);
- ResultSet resultSet = ps.executeQuery();
- while(resultSet.next()){
- System.out.println(resultSet.getString("username") + " " +resultSet.getString("password"));
- }
- System.out.println("======往TEST表中插入数据======");
- sql = "insert into TEST (USERNAME, PASSWORD) values ('TestInsert', '1234') ";
- ps = conn.prepareStatement(sql);
- ps.executeUpdate();
- System.out.println("======遍历TEST表所有的数据(插入之后)======");
- sql = "select username,password from TEST ";
- ps = conn.prepareStatement(sql);
- resultSet = ps.executeQuery();
- while(resultSet.next()){
- System.out.println(resultSet.getString("username") + " " +resultSet.getString("password"));
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }finally {
- conn.close();
- }
- }
- }
日志输出:
- ======遍历TEST表所有的数据======
- Obama 1234
- John 1234
- Mike 1234
- Jim 1234
- Ana 1234
- Ennerson 1234
- ======往TEST表中插入数据======
- ======遍历TEST表所有的数据(插入之后)======
- TestInsert 1234
- Obama 1234
- John 1234
- Mike 1234
- Jim 1234
- Ana 1234
- Ennerson 1234