Home > Java > javaTutorial > java special topic about JDBC

java special topic about JDBC

Y2J
Release: 2017-04-24 11:08:33
Original
1294 people have browsed it

JDBC (connection to Oracle)

JDBC programming steps:
----Connection between java and Oracle data
1.Find the jdbc folder → lib folder → classesl2.jar in the Oracle database installation folder (Choose different jars according to jre Package )
## 2. Import this Jar package into eclipse
Import method:
##Create a project, right-click on the project name and select Build Path→Add External Archives→##                                                          Select classesl2.jar to import
3. Create a new program to write the code to connect to Oracle

The steps are as follows:
1. Example driver class

 class.forName("
Oracle.jdbc.driver.OracleDriver
");
Copy after login

#2. Create the connection to the database

#

 
 Connection conn = DriverManager.getConnection("jdbc:oracle:thin:
                            @192.168.8.1:1521:yuewei","scott","tiger");
Copy after login

## 3.

Obtain an object that executes a sql statement based on the connection

 Statement stm = conn.CreatStatement();
Copy after login
      4. Execute the statement (select statement)

 ResultSet rs = stm.executeQuery(select * from dept);
Copy after login
                                                                                                                  Display statement

rs.getString("deptno");
Copy after login

##JDBC connection database

  1. •Create a program to connect to the database using JDBC, including

  2. 7

    steps:

  3. 1

    . Load the JDBC driver: # Before connecting to the database, you must first load the driver of the database you want to connect to the JVM (Java Virtual Machine),

  4. This is achieved through the static method forName(String className) of the java.lang.Class class.

  5. For example:

  6. try{

  7. //加载MySql的驱动类

  8.  Class.forName("com.mysql.jdbc.Driver") ;
       
        }catch(ClassNotFoundException e){
       
        System.out.println("找不到驱动程序类 ,加载驱动失败!");
       
        e.printStackTrace() ;   
        }
    Copy after login
  9. 成功加载后,会将Driver类的实例注册到DriverManager类中。

  10. 2、提供JDBC连接的URL

  11. •连接URL定义了连接数据库时的协议、子协议、数据源标识。

  12. •书写形式:协议:子协议:数据源标识

  13. 协议:在JDBC中总是以jdbc开始

  14. 子协议:是桥连接的驱动程序或是数据库管理系统名称。

  15. 数据源标识:标记找到数据库来源的地址与连接端口。

  16. 例如:(MySql的连接URL)

  17. jdbc:mysql:

  18. //localhost:3306/test?useUnicode=true&characterEncoding=gbk ;

  19. useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为

  20. gb2312或GBK,本参数必须设置为true 。characterEncoding=gbk:字符编码方式。

  21. 3、创建数据库的连接

  22. •要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,

  23. 该对象就代表一个数据库的连接。

  24. •使用DriverManager的getConnectin(String url , String username ,

  25. String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和

  26. 密码来获得。

  27. 例如:

  28. //连接MySql数据库,用户名和密码都是root

  29.   String url = "jdbc:mysql://localhost:3306/test" ; 
         String username = "root" ;
         String password = "root" ;
         try{
        Connection con =    
                 DriverManager.getConnection(url , username , password ) ;   
         }catch(SQLException se){
        System.out.println("数据库连接失败!");
        se.printStackTrace() ;   
         }
    Copy after login
  30. 4、创建一个Statement

  31. •要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3

  32. 种类型:

  33. 1、执行静态SQL语句。通常通过Statement实例实现。

  34. 2、执行动态SQL语句。通常通过PreparedStatement实例实现。

  35. 3、执行数据库存储过程。通常通过CallableStatement实例实现。

  36. 具体的实现方式:

  37. Statement stmt = con.createStatement() ;

  38. PreparedStatement pstmt = con.prepareStatement(sql) ;

  39. CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;

  40. 5、执行SQL语句

  41. Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate

  42. 和execute

  43. 1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句

  44. ,返回一个结果集(ResultSet)对象。

  45. 2int executeUpdate(String sqlString):用于执行INSERT、UPDATE或

  46. DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等

  47. 3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的

  48. 语句。

  49. 具体实现的代码:

  50.  ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
          int rows = stmt.executeUpdate("INSERT INTO ...") ;
          boolean flag = stmt.execute(String sql) ;
    Copy after login
  51. 6、处理结果

  52. 两种情况:

  53. 1、执行更新返回的是本次操作影响到的记录数。

  54. 2、执行查询返回的结果是一个ResultSet对象。

  55. • ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些

  56. 行中数据的访问。

  57. • 使用结果集(ResultSet)对象的访问方法获取数据:

  58.  while(rs.next()){
             String name = rs.getString("name") ;
        String pass = rs.getString(1) ; // 此方法比较高效   
         }
    Copy after login
  59. (列是从左到右编号的,并且从列1开始)

  60. 7、关闭JDBC对象

  61. 操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声

  62. 明顺序相反:

  63. 1、关闭记录集

  64. 2、关闭声明

  65. 3、关闭连接对象

  66.  if(rs != null){   // 关闭记录集   
            try{
                rs.close() ;   
            }catch(SQLException e){
                e.printStackTrace() ;   
            }   
              }   
              if(stmt != null){   // 关闭声明   
            try{
                stmt.close() ;   
            }catch(SQLException e){
                e.printStackTrace() ;   
            }   
              }   
              if(conn != null){  // 关闭连接对象   
             try{
                conn.close() ;   
             }catch(SQLException e){
                e.printStackTrace() ;   
             }   
              }
    Copy after login

<pre name="code" class="java">import java.sql.*;  
public class TestJDBC {  
 public static void main(String[] args) {  
  ResultSet rs = null;  
  Statement stmt = null;  
  Connection conn = null;  

     //连接数据库,用户名和密码都是root   
     String url = "jdbc:oracle:thin:@192.168.1.56:1521:yuewei" ;    
     String username = "root" ;   
     String password = "root" ;   
  try {  
   Class.forName("oracle.jdbc.driver.OracleDriver");  //加载数据库的驱动类
   conn = DriverManager.getConnection(url, username, password);  
   stmt = conn.createStatement();  
   rs = stmt.executeQuery("select * from kkk");   
   while(rs.next()) {  
    System.out.println(rs.getString(1)); // 此方法比较高效  (列是从左到右编号的,并且从列1开始)         
   }  
  } catch (ClassNotFoundException e) {  
   e.printStackTrace();  
  } catch (SQLException e) {  
   e.printStackTrace();  
  } finally {  
   try {  
    if(rs != null) {  
     rs.close();  
     rs = null;  
    }  
    if(stmt != null) {  
     stmt.close();  
     stmt = null;  
    }  
    if(conn != null) {  
     conn.close();  
     conn = null;  
    }  
   } catch (SQLException e) {  
    e.printStackTrace();  
   }  
  }  
 }  
  
}
Copy after login

The above is the detailed content of java special topic about JDBC. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template