整理日志7-JDBC总结.

本文详细介绍了使用JDBC进行数据库操作的基本步骤,包括加载驱动、建立连接、执行SQL语句等,并提供了针对不同数据库的具体示例。

使用JDBC进行访问数据库,首先要确保安装和运行了选择的数据库,并且驱动程序可用。(可以从 http://industry.java.sun.com/products/jdbc/drivers 下载 JDBC 驱动程序)
Java与数据库交互通常由以下几步组成:
     1.装入数据库驱动程序 (JDBC 驱动程序或 JDBC-ODBC 桥) 。
     2.创建数据库的 Connection。
     3.创建一个 Statement 对象。该对象实际执行 SQL 或存储过程。
     4.创建一个 ResultSet,然后用执行查询的结果填充(如果目标是检索或直接更新数据)。
     5.从 ResultSet 检索或更新数据。

一、实例化驱动

访问数据库,先装入 JDBC 驱动程序,然后由 DriverManager创建与数据库相应的驱动程序的连接来确定。使用Class.forName() 直接装入,向 DriverManager 注册
示例:
public class Pricing extends Object {

   public static void main (String args[]){

       String driverName = "JData2_0.sql.$Driver";

      try {
         Class.forName(driverName);
      } catch (ClassNotFoundException e) {
         System.out.println("Error creating class: "+e.getMessage());
      }
   }
}

二、创建Connection

示例:
import .sql.Connection;
import .sql.DriverManager;
import .sql.SQLException;

public class Pricing extends Object {
   public static void main (String args[]){
      String driverName = "JData2_0.sql.$Driver";
      String connectURL =
      "jdbc:JDataConnect://127.0.0.1/pricing";
      Connection conn = null;   
      try
      {
         Class.forName(driverName);
         conn = DriverManager.getConnection(connectURL);
      } catch (ClassNotFoundException e) {
         System.out.println("Error creating class: "+e.getMessage());
      } catch (SQLException e) {
          System.out.println("Error creating connection:"+e.getMessage());
      }
      finally {
         System.out.println("Closing connections...");
         try {
            conn.close();
         } catch (SQLException e) {
            System.out.println("Can't close connection.");
         }
      }

   }
}
各种数据库使用JDBC连接的方式
//DB2
String driverName = "com.ibm.db2.jcc.DB2Driver";
String connectURL = "jdbc:db2://localhost:5000/sample";
Class.forName(driverName);
Connection conn = DriverManager.getConnection(connectURL,”user”,”password”);

//Oracle(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="test";
String password="test";
Connection conn= DriverManager.getConnection(url,user,password);

//SQL
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb"; String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);

//Sybase
Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/myDB";
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);

//MySQL
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1" Connection conn= DriverManager.getConnection(url);

//ACCESS
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
String url="jdbc:odbc:Driver={MicroSoft Access Driver(*.mdb)};DBQ="+application.getRealPath("/Data/MyDb.mdb");
Connection conn = DriverManager.getConnection(url,"","");
Statement stmtNew=conn.createStatement() ;

三、创建 Statement 对象

Statement 对象用于将 SQL 语句发送到数据库中。有三种 Statement 对象,它们都作为在给定连接上执行 SQL 语句的包容器:Statement、PreparedStatement(它从Statement 继承而来)和 CallableStatement(它从 PreparedStatement 继承而来)。它们都专用于发送特定类型的 SQL 语句: Statement 对象用于执行不带参数的简单SQL 语句;PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句(当要反复执行某一特定查询时,PreparedStatement 可能最有用);CallableStatement 对象用于执行对数据库已存储过程的调用。CallableStatement 和 PreparedStatement之间的一个区别是:除了通常创建的 ResultSet 之外,CallableStatement 还可以提供 OUT 参数

Statement实例:
在程序中增加
import .sql.Statement;
在程序生成Connection对象后,利用该对象生成Statement 对象
Statement statement = null;
      try {
         statement = conn.createStatement();
      } catch (SQLException e) {
         System.out.println("SQL Error: "+e.getMessage());
      }

PreparedStatement实例
...
 statement = conn.prepareStatement("select * from test where "+ "id < ? and id > ?");
 statement.setInt(1, 5);
 statement.setInt(2, 10);
 resultset = statement.executeQuery();
...
CallableStatement实例

四、执行Statement

Statement 接口提供了三种执行 SQL 语句的方法:executeQuery、executeUpdate 和execute。使用哪一个方法由 SQL 语句所产生的内容决定。

  方法 executeQuery 用于产生单个结果集的语句,例如 SELECT 语句。
  方法 executeUpdate 用于执行 INSERT、UPDATE 或 DELETE 语句以及 SQL DDL(数据定义语言)语句,例如 CREATE TABLE 和 DROP TABLE。INSERT、UPDATE 或DELETE 语句的效果是修改表中零行或多行中的一列或多列。executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 CREATE TABLE 或 DROP TABLE 等不操作行的语句,executeUpdate 的返回值总为零。
  方法 execute 用于执行返回多个结果集、多个更新计数或二者组合的语句。

示例:
import .sql.ResultSet;
ResultSet Rs = null;
在生成Statement后执行
Rs = statement.executeQuery("SELECT * FROM test");

五、ResultSet

ResultSet 被创建之后,它就有一个引用数据集内相对位置的“指针”。在 ResultSet语句返回之后(即使表为空),该指针正好位于第一行的“上面”。要到达实际数据的第一行,应用程序调用 next() 方法。该方法返回一个 Boolean 值,指出在新位置处是否有行存在。如果没发现数据,则 next() 返回 false。
Getxxx()与wasNull()
ResultSet.getXXX 方法获取常见的 JDBC 数据类型
对非常大的行值使用流
getBinaryStream 返回只提供数据库原字节而不进行任何转换的流。
getAsciiStream 返回提供单字节 ASCII 字符的流。
getUnicodeStream 返回提供双字节 Unicode 字符的流。
wasNull() 方法来确定是否有特定的数据片为空
while (resultset.next()) {
//根据字段名
System.out.print(resultset.getString("id"));
//根据索引
System.out.print(resultset.getString(2));
……
}
通过ResultSetMetaData类还可以获取元数据
...
import .sql.ResultSetMetaData;
public class Pricing extends Object {
...
      Statement statement = null;
      ResultSet resultset = null;
      ResultSetMetaData resultmetadata = null;
      try {
         statement = conn.createStatement();
         resultset = statement.executeQuery("select * from products");
  
         //Get the ResultSet information
         resultmetadata = resultset.getMetaData();
         //Determine the number of columns in the ResultSet
         int numCols = resultmetadata.getColumnCount();
  
         while (resultset.next()) {
            for (int i=1; i <= numCols; i++) {
               //For each column index, determine the column name
               String colName = resultmetadata.getColumnName(i);
               //Get the column value
               String colVal = resultset.getString(i);
               //Output the name and value
               System.out.println(colName+"="+colVal);
            }
            //Output a line feed at the end of the row
            System.out.println(" ");
         }
...
不必关闭 ResultSet;当产生它的 Statement 关闭、重新执行或用于从多结果序列中获取下一个结果时,该 ResultSet 将被 Statement 自动关闭。

 

排查结果如下: 1.使用mvn dependency:tree返回如下信息: [INFO] --- maven-dependency-plugin:3.1.2:tree (default-cli) @ zysygh --- [INFO] com.ghzy:zysygh:jar:0.1.196 [INFO] +- org.springframework.boot:spring-boot-starter-data-redis:jar:2.2.13.RELEASE:compile [INFO] | +- org.springframework.boot:spring-boot-starter:jar:2.2.13.RELEASE:compile [INFO] | | +- org.springframework.boot:spring-boot:jar:2.2.13.RELEASE:compile [INFO] | | +- org.springframework.boot:spring-boot-autoconfigure:jar:2.2.13.RELEASE:compile [INFO] | | +- jakarta.annotation:jakarta.annotation-api:jar:1.3.5:compile [INFO] | | \- org.yaml:snakeyaml:jar:1.25:runtime [INFO] | +- org.springframework.data:spring-data-redis:jar:2.2.12.RELEASE:compile [INFO] | | +- org.springframework.data:spring-data-keyvalue:jar:2.2.12.RELEASE:compile [INFO] | | | \- org.springframework.data:spring-data-commons:jar:2.2.12.RELEASE:compile [INFO] | | +- org.springframework:spring-tx:jar:5.2.12.RELEASE:compile [INFO] | | +- org.springframework:spring-oxm:jar:5.2.12.RELEASE:compile [INFO] | | \- org.springframework:spring-aop:jar:5.2.12.RELEASE:compile [INFO] | \- io.lettuce:lettuce-core:jar:5.2.2.RELEASE:compile [INFO] | +- io.netty:netty-common:jar:4.1.58.Final:compile [INFO] | +- io.netty:netty-handler:jar:4.1.58.Final:compile [INFO] | | +- io.netty:netty-resolver:jar:4.1.58.Final:compile [INFO] | | +- io.netty:netty-buffer:jar:4.1.58.Final:compile [INFO] | | \- io.netty:netty-codec:jar:4.1.58.Final:compile [INFO] | +- io.netty:netty-transport:jar:4.1.58.Final:compile [INFO] | \- io.projectreactor:reactor-core:jar:3.3.13.RELEASE:compile [INFO] | \- org.reactivestreams:reactive-streams:jar:1.0.3:compile [INFO] +- org.springframework.boot:spring-boot-starter-mail:jar:2.2.13.RELEASE:compile [INFO] | +- org.springframework:spring-context-support:jar:5.2.12.RELEASE:compile [INFO] | | +- org.springframework:spring-beans:jar:5.2.12.RELEASE:compile [INFO] | | \- org.springframework:spring-context:jar:5.2.12.RELEASE:compile [INFO] | \- com.sun.mail:jakarta.mail:jar:1.6.5:compile [INFO] | \- com.sun.activation:jakarta.activation:jar:1.2.2:compile [INFO] +- org.springframework.boot:spring-boot-starter-thymeleaf:jar:2.2.13.RELEASE:compile [INFO] | +- org.thymeleaf:thymeleaf-spring5:jar:3.0.12.RELEASE:compile [INFO] | | \- org.thymeleaf:thymeleaf:jar:3.0.12.RELEASE:compile [INFO] | | +- org.attoparser:attoparser:jar:2.0.5.RELEASE:compile [INFO] | | \- org.unbescape:unbescape:jar:1.1.6.RELEASE:compile [INFO] | \- org.thymeleaf.extras:thymeleaf-extras-java8time:jar:3.0.4.RELEASE:compile [INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.2.13.RELEASE:compile [INFO] | +- org.springframework.boot:spring-boot-starter-json:jar:2.2.13.RELEASE:compile [INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.10.5:compile [INFO] | | +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.10.5:compile [INFO] | | \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.10.5:compile [INFO] | +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.2.13.RELEASE:compile [INFO] | | +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.41:compile [INFO] | | +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.41:compile [INFO] | | \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.41:compile [INFO] | +- org.springframework.boot:spring-boot-starter-validation:jar:2.2.13.RELEASE:compile [INFO] | | +- jakarta.validation:jakarta.validation-api:jar:2.0.2:compile [INFO] | | \- org.hibernate.validator:hibernate-validator:jar:6.0.22.Final:compile [INFO] | | +- org.jboss.logging:jboss-logging:jar:3.4.1.Final:compile [INFO] | | \- com.fasterxml:classmate:jar:1.5.1:compile [INFO] | +- org.springframework:spring-web:jar:5.2.12.RELEASE:compile [INFO] | \- org.springframework:spring-webmvc:jar:5.2.12.RELEASE:compile [INFO] | \- org.springframework:spring-expression:jar:5.2.12.RELEASE:compile [INFO] +- org.mybatis.spring.boot:mybatis-spring-boot-starter:jar:2.3.2:compile [INFO] | +- org.springframework.boot:spring-boot-starter-jdbc:jar:2.2.13.RELEASE:compile [INFO] | | +- com.zaxxer:HikariCP:jar:3.4.5:compile [INFO] | | \- org.springframework:spring-jdbc:jar:5.2.12.RELEASE:compile [INFO] | +- org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:jar:2.3.2:compile [INFO] | \- org.mybatis:mybatis-spring:jar:2.1.2:compile [INFO] +- org.springframework.boot:spring-boot-starter-logging:jar:2.2.13.RELEASE:compile [INFO] | +- ch.qos.logback:logback-classic:jar:1.2.3:compile [INFO] | | \- ch.qos.logback:logback-core:jar:1.2.3:compile [INFO] | \- org.slf4j:jul-to-slf4j:jar:1.7.30:compile [INFO] +- mysql:mysql-connector-java:jar:8.0.26:runtime [INFO] +- org.projectlombok:lombok:jar:1.18.16:compile (optional) [INFO] +- org.springframework.boot:spring-boot-starter-test:jar:2.2.13.RELEASE:test [INFO] | +- org.springframework.boot:spring-boot-test:jar:2.2.13.RELEASE:test [INFO] | +- org.springframework.boot:spring-boot-test-autoconfigure:jar:2.2.13.RELEASE:test [INFO] | +- com.jayway.jsonpath:json-path:jar:2.4.0:test [INFO] | | \- net.minidev:json-smart:jar:2.3:test [INFO] | | \- net.minidev:accessors-smart:jar:1.2:test [INFO] | | \- org.ow2.asm:asm:jar:5.0.4:test [INFO] | +- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.3:test [INFO] | | \- jakarta.activation:jakarta.activation-api:jar:1.2.2:test [INFO] | +- org.junit.jupiter:junit-jupiter:jar:5.5.2:test [INFO] | | +- org.junit.jupiter:junit-jupiter-api:jar:5.5.2:test [INFO] | | | +- org.opentest4j:opentest4j:jar:1.2.0:test [INFO] | | | \- org.junit.platform:junit-platform-commons:jar:1.5.2:test [INFO] | | +- org.junit.jupiter:junit-jupiter-params:jar:5.5.2:test [INFO] | | \- org.junit.jupiter:junit-jupiter-engine:jar:5.5.2:test [INFO] | +- org.junit.vintage:junit-vintage-engine:jar:5.5.2:test [INFO] | | +- org.apiguardian:apiguardian-api:jar:1.1.0:test [INFO] | | +- org.junit.platform:junit-platform-engine:jar:1.5.2:test [INFO] | | \- junit:junit:jar:4.12:test [INFO] | +- org.mockito:mockito-junit-jupiter:jar:3.1.0:test [INFO] | +- org.assertj:assertj-core:jar:3.13.2:test [INFO] | +- org.hamcrest:hamcrest:jar:2.1:test [INFO] | +- org.mockito:mockito-core:jar:3.1.0:test [INFO] | | +- net.bytebuddy:byte-buddy:jar:1.10.19:test [INFO] | | +- net.bytebuddy:byte-buddy-agent:jar:1.10.19:test [INFO] | | \- org.objenesis:objenesis:jar:2.6:test [INFO] | +- org.skyscreamer:jsonassert:jar:1.5.0:test [INFO] | | \- com.vaadin.external.google:android-json:jar:0.0.20131108.vaadin1:test [INFO] | +- org.springframework:spring-core:jar:5.2.12.RELEASE:compile [INFO] | | \- org.springframework:spring-jcl:jar:5.2.12.RELEASE:compile [INFO] | +- org.springframework:spring-test:jar:5.2.12.RELEASE:test [INFO] | \- org.xmlunit:xmlunit-core:jar:2.6.4:test [INFO] +- com.aliyun:aliyun-java-sdk-core:jar:4.5.3:compile [INFO] | +- com.google.code.gson:gson:jar:2.8.6:compile [INFO] | +- org.apache.httpcomponents:httpclient:jar:4.5.13:compile [INFO] | | \- commons-codec:commons-codec:jar:1.13:compile [INFO] | +- org.apache.httpcomponents:httpcore:jar:4.4.14:compile [INFO] | +- commons-logging:commons-logging:jar:1.2:compile [INFO] | +- javax.xml.bind:jaxb-api:jar:2.3.1:compile [INFO] | | \- javax.activation:javax.activation-api:jar:1.2.0:compile [INFO] | +- org.jacoco:org.jacoco.agent:jar:runtime:0.8.5:compile [INFO] | +- org.ini4j:ini4j:jar:0.5.4:compile [INFO] | +- org.slf4j:slf4j-api:jar:1.7.30:compile [INFO] | +- io.opentracing:opentracing-api:jar:0.33.0:compile [INFO] | \- io.opentracing:opentracing-util:jar:0.33.0:compile [INFO] | \- io.opentracing:opentracing-noop:jar:0.33.0:compile [INFO] +- com.aliyun:dysmsapi20170525:jar:4.1.0:compile [INFO] | +- com.aliyun:tea-util:jar:0.2.23:compile [INFO] | +- com.aliyun:endpoint-util:jar:0.0.7:compile [INFO] | +- com.aliyun:tea:jar:1.3.1:compile [INFO] | | \- com.squareup.okhttp3:okhttp:jar:3.14.9:compile [INFO] | | \- com.squareup.okio:okio:jar:1.17.2:compile [INFO] | +- com.aliyun:tea-openapi:jar:0.3.8:compile [INFO] | | +- com.aliyun:credentials-java:jar:1.0.1:compile [INFO] | | | \- com.aliyun:credentials-api:jar:1.0.0:compile [INFO] | | +- com.aliyun:alibabacloud-gateway-spi:jar:0.0.2:compile [INFO] | | \- com.aliyun:tea-xml:jar:0.1.6:compile [INFO] | | \- org.dom4j:dom4j:jar:2.0.3:compile [INFO] | \- com.aliyun:openapiutil:jar:0.2.2:compile [INFO] | \- org.bouncycastle:bcprov-jdk18on:jar:1.78.1:compile [INFO] +- com.alibaba:fastjson:jar:1.2.75:compile [INFO] +- org.mybatis:mybatis:jar:3.5.9:compile [INFO] +- org.jetbrains:annotations:jar:13.0:compile [INFO] +- org.springframework.boot:spring-boot-configuration-processor:jar:2.2.13.RELEASE:compile (optional) [INFO] +- redis.clients:jedis:jar:3.1.0:compile [INFO] | \- org.apache.commons:commons-pool2:jar:2.7.0:compile [INFO] +- io.jsonwebtoken:jjwt-api:jar:0.11.5:compile [INFO] +- io.jsonwebtoken:jjwt-impl:jar:0.11.5:runtime [INFO] \- io.jsonwebtoken:jjwt-jackson:jar:0.11.5:runtime [INFO] \- com.fasterxml.jackson.core:jackson-databind:jar:2.10.5.1:compile [INFO] +- com.fasterxml.jackson.core:jackson-annotations:jar:2.10.5:compile [INFO] \- com.fasterxml.jackson.core:jackson-core:jar:2.10.5:compile [INFO] ------------------------------------------------------------------------ 2.applicaion.properties中的配置内容为logging.config=classpath:logback-spring.xml 3.src/main/resources目录下存在logback-spring.xml文件,但之前里面没有那两行<include>配置项,现已添加。
最新发布
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值