首页 > 代码库 > JDBC

JDBC

JDBC(java访问数据库的解决方案)
JDBC定义了一套标准的接口,不同的数据库厂商根据各自数据库的特点去实现这些接口.

JDBC工作过程:
1)加载驱动,建立连接<br>
2)创建语句对象<br>
3)执行SQL语句<br>
4)处理结果集<br>
5)关闭连接<br>

    
 * JDBC中的主要接口:
 * DriverManager:负责加载驱动,建立与数据库的连接
 * Connection:表示与数据库的一个连接,负责创建
 *            Statement
 * Statement:负责向数据库执行SQL语句
 * ResultSet:表示数据库的一个查询结果集           
 
public class JDBCDemo{<br>
    public static void main(String[] args) {<br>
        try {<br>
            //1:加载驱动,不同的数据库字符串的内容不一样。<br>
            Class.forName("oracle.jdbc.driver.OracleDriver");<br>
            // 2:使用DriverManager通过加载的驱动与数据库建立连接 DriverManager的静态方法getConnection用于
                与数据库建立连接,需要传入三个参数
                参数1:数据库的地址(不同数据库格式不一样)
                参数2:数据库的用户名
                参数3:数据库的密码<br>
              
            Connection conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@192.168.201.217:1521:orcl",
                "openlab",
                "open123"
            );
            System.out.println("已连接数据库!");
            
            
             // 3:创建Statement以发送SQL语句
             
            Statement state = conn.createStatement();
            
            String sql = "CREATE TABLE userinfo( "
                       + "    id NUMBER(6), "
                       + "  username VARCHAR2(50), "
                       + "  password VARCHAR2(50), "
                       + "  email VARCHAR2(100), "
                       + "  nickname VARCHAR2(50), "
                       + "  account NUMBER(10,2) "
                       + ")";
            //处理结果集
            ResultSet rs = state.executeQuery(sql);
                while(rs.next()){
                    //获取id
                    int id = rs.getInt("id");
                    //获取username
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    String email = rs.getString("email");
                    String nickName = rs.getString("nickname");
                    double account = rs.getDouble("account");
                    System.out.println(id+","+username+","+password+","+email+","+nickName+","+account);
                }
            //没有其他数据库操作则关闭数据库连接
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}





JDBC