对于JDBC获取Oracle数据库连接感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍使用Driver,并为您提供关于2.通过原始的Driver接口通过读取Properties属性文件获取JDB
对于JDBC 获取 Oracle 数据库连接感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍使用 Driver,并为您提供关于2. 通过原始的 Driver 接口通过读取 Properties 属性文件获取 JDBC 数据库连接 Connection、Caused by: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jd、ClassCastException:无法将oracle.jdbc.driver.T4CConnection强制转换为oracle.jdbc.OracleConnection、com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver的有用信息。
本文目录一览:- JDBC 获取 Oracle 数据库连接(使用 Driver)(jdbc获取oracle表结构)
- 2. 通过原始的 Driver 接口通过读取 Properties 属性文件获取 JDBC 数据库连接 Connection
- Caused by: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jd
- ClassCastException:无法将oracle.jdbc.driver.T4CConnection强制转换为oracle.jdbc.OracleConnection
- com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver
JDBC 获取 Oracle 数据库连接(使用 Driver)(jdbc获取oracle表结构)
获取数据库连接的方法:
1. Driver 接口:
•Java.sql.Driver 接口是所有 JDBC 驱动程序需要实现的接口。这个接口是提供给数据库厂商使用的,不同数据库厂商提供不同的实现
•在程序中不需要直接去访问实现了 Driver 接口的类,而是由驱动程序管理器类(java.sql.DriverManager)去调用这些Driver实现
2. 加载与注册JDBC 驱动:
•加载 JDBC 驱动需调用 Class 类的静态方法 forName(),向其传递要加载的 JDBC 驱动的类名
•DriverManager 类是驱动程序管理器类,负责管理驱动程序
•通常不用显式调用 DriverManager 类的 registerDriver() 方法来注册驱动程序类的实例,因为 Driver 接口的驱动程序类都包含了静态代码块,在这个静态代码块中,会调用 DriverManager.registerDriver() 方法来注册自身的一个实例
3. 建立连接:
•可以调用 DriverManager 类的 getConnection() 方法建立到数据库的连接
•JDBC URL 用于标识一个被注册的驱动程序,驱动程序管理器通过这个 URL 选择正确的驱动程序,从而建立到数据库的连接。
•JDBC URL的标准由三部分组成,各部分间用冒号分隔。
–jdbc:<子协议>:<子名称>
–协议:JDBC URL中的协议总是jdbc
–子协议:子协议用于标识一个数据库驱动程序
–子名称:一种标识数据库的方法。子名称可以依不同的子协议而变化,用子名称的目的是为了定位数据库提供足够的信息
public Connection getConnection() throws Exception{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
InputStream in =
getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
// 通过反射创建 Driver 对象
Driver driver =
(Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
// 通过 Driver 的connect 方法获取数据库连接
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}
@Test
public void testGetConnection() throws Exception{
System.out.println(getConnection());
}
// jdbc.properties 文件
driver=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost :1521:orcl
user=scott
password=tiger
2. 通过原始的 Driver 接口通过读取 Properties 属性文件获取 JDBC 数据库连接 Connection
/**
* 编写一个通用的方法, 在不修改源程序的情况下, 可以获取任何数据库的连接
* 解决方案: 把数据库驱动 Driver 实现类的全类名、url、user、password 放入一个
* 配置文件中, 通过修改配置文件的方式实现和具体的数据库解耦.
* @throws Exception
*/
public Connection getConnection() throws Exception{
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//读取类路径下的 jdbc.properties 文件
InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password");
//通过反射常见 Driver 对象.
Driver driver =
(Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
//通过 Driver 的 connect 方法获取数据库连接.
Connection connection = driver.connect(jdbcUrl, info);
return connection;
}
Caused by: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jd
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jdbc:mysql//localhost:3306/cache
### The error may exist in com/pshdhx/cache/mapper/Employeemapper.java (best guess)
### The error may involve com.pshdhx.cache.mapper.Employeemapper.getEmployee
### The error occurred while executing a query
### Cause: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jdbc:mysql//localhost:3306/cache
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:96)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:441)
at com.sun.proxy.$Proxy73.selectOne(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:160)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:87)
at org.apache.ibatis.binding.MapperProxy$PlainMethodInvoker.invoke(MapperProxy.java:152)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85)
at com.sun.proxy.$Proxy79.getEmployee(Unknown Source)
springboot连接mysql查询,是字段没有对应上出的错,一开始我是以为连接mysql出了问题;
ClassCastException:无法将oracle.jdbc.driver.T4CConnection强制转换为oracle.jdbc.OracleConnection
如何解决ClassCastException:无法将oracle.jdbc.driver.T4CConnection强制转换为oracle.jdbc.OracleConnection
当我尝试与Oracle数据库建立连接时,我遇到了这个问题。我的应用程序规格是java8 + ejb + jboss-eap-7.3 + oracle 12c
请在下面找到我的代码详细信息
我的pom.xml
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>14</version>
<type>ejb</type>
<scope>provided</scope>
<dependency>
我已从路径jboss-ep-7.3/modules/com/oracle/ojdbc/main
在module.xml文件中添加了“ ojdbc6.jar”。
My DBConnection.java
CallableStatement statement;
Connection connection;
ArrayDescriptor descriptor;
Connection conn = datasourceObj.getconnection(dev);
try {
statement = conn.prepareCall(callString);
connection = ((WrappedConnection)
conn).getUnderlyingConnection();
descriptor = ArrayDescriptor.createDescriptor("NUM_ARRAY",connection);
}
将此EAR部署到jboss 7.3中之后,出现以下错误
由于:java.lang.classCastException: 无法强制转换org.jboss.jca.adapters.jdbc.jdk8.WrappedConnectionJDK8 到oracle.jdbc.OracleConnection
我替换下面的代码
connection = ((WrappedConnection) conn).getUnderlyingConnection();
使用这段代码
OracleConnection oracleConnection = (OracleConnection) conn.getClass().getmethod("getUnderlyingConnection").invoke(conn);
此代码更改后得到
ClassCastException:oracle.jdbc.driver.T4CConnection无法强制转换为 oracle.jdbc.OracleConnection
我什至删除了classes12.jar,但没有任何进展。我需要对oracle19c做同样的事情。请给出您的宝贵意见以解决此问题。
com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver
com.mysql.jdbc.Driver
tocom.mysql.cj.jdbc.Driver
MySQL :: MySQL Connector/J 8.0 Developer Guide :: 4.3.1.3 Changes in the Connector/J API https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-api-changes.html
4.3.1.3 Changes in the Connector/J API
This section describes the changes to the Connector/J API going from version 5.1 to 8.0. You might need to adjust your API calls accordingly:
-
The name of the class that implements
java.sql.Driver
in MySQL Connector/J has changed fromcom.mysql.jdbc.Driver
tocom.mysql.cj.jdbc.Driver
. The old class name has been deprecated. -
The names of these commonly-used interfaces have also been changed:
-
ExceptionInterceptor: from
com.mysql.jdbc.ExceptionInterceptor
tocom.mysql.cj.exceptions.ExceptionInterceptor
-
StatementInterceptor: from
com.mysql.jdbc.StatementInterceptorV2
tocom.mysql.cj.interceptors.QueryInterceptor
-
ConnectionLifecycleInterceptor: from
com.mysql.jdbc.ConnectionLifecycleInterceptor
tocom.mysql.cj.jdbc.interceptors.ConnectionLifecycleInterceptor
-
AuthenticationPlugin: from
com.mysql.jdbc.AuthenticationPlugin
tocom.mysql.cj.protocol.AuthenticationPlugin
-
BalanceStrategy: from
com.mysql.jdbc.BalanceStrategy
tocom.mysql.cj.jdbc.ha.BalanceStrategy
. -
-
信息: Loading XML bean definitions from class path resource [Beans.xml]
Loading class `com.mysql.jdbc.Driver''. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver''. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
<bean id="dataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://rm-2zeo.mysql.rds.aliyuncs.com:3306/vtest"/>
<property name="username" value="u"/>
<property name="password" value="I"/>
</bean>
<!-- Definition for studentJDBCTemplate bean -->
<bean id="studentJDBCTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
mvn clean;mvn compile;mvn package;mvn install;
mvn 打包jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>HelloSpringJDBCMysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>
<build>
<!--使用的插件列表-->
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.tutorialspoint.MainApp</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>com.tutorialspoint.MainApp</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
[root@d java]# tree -I target
.
├── pom.xml
├── spring.iml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── tutorialspoint
│ │ ├── MainApp.java
│ │ ├── StudentDAO.java
│ │ ├── Student.java
│ │ ├── StudentJDBCTemplate.java
│ │ └── StudentMapper.java
│ └── resources
│ └── beans.xml
└── test
└── java
8 directories, 8 files
[root@d java]#
com.tutorialspoint.StudentDAO
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
public interface StudentDAO {
/**
* This is the method to be used to initialize
* database resources ie. connection.
*/
public void setDataSource(DataSource ds);
/**
* This is the method to be used to create
* a record in the Student table.
*/
public void create(String name, Integer age);
/**
* This is the method to be used to list down
* a record from the Student table corresponding
* to a passed student id.
*/
public Student getStudent(Integer id);
/**
* This is the method to be used to list down
* all the records from the Student table.
*/
public List<Student> listStudents();
/**
* This is the method to be used to delete
* a record from the Student table corresponding
* to a passed student id.
*/
public void delete(Integer id);
/**
* This is the method to be used to update
* a record into the Student table.
*/
public void update(Integer id, Integer age);
}
com.tutorialspoint.Student
package com.tutorialspoint;
public class Student {
/**
CREATE TABLE Student(
ID INT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
* */
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
com.tutorialspoint.StudentMapper
package com.tutorialspoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
com.tutorialspoint.StudentJDBCTemplate
package com.tutorialspoint;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class StudentJDBCTemplate implements StudentDAO {
private DataSource dataSource;
private JdbcTemplate jdbcTemplateObject;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplateObject = new JdbcTemplate(dataSource);
}
public void create(String name, Integer age) {
String SQL = "insert into Student (name, age) values (?, ?)";
jdbcTemplateObject.update( SQL, name, age);
System.out.println("Created Record Name = " + name + " Age = " + age);
return;
}
public Student getStudent(Integer id) {
String SQL = "select * from Student where id = ?";
Student student = jdbcTemplateObject.queryForObject(SQL,
new Object[]{id}, new StudentMapper());
return student;
}
public List<Student> listStudents() {
String SQL = "select * from Student";
List <Student> students = jdbcTemplateObject.query(SQL,
new StudentMapper());
return students;
}
public void delete(Integer id){
String SQL = "delete from Student where id = ?";
jdbcTemplateObject.update(SQL, id);
System.out.println("Deleted Record with ID = " + id );
return;
}
public void update(Integer id, Integer age){
String SQL = "update Student set age = ? where id = ?";
jdbcTemplateObject.update(SQL, age, id);
System.out.println("Updated Record with ID = " + id );
return;
}
}
com.tutorialspoint.MainApp
package com.tutorialspoint;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
//ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
//ApplicationContext context = new ClassPathXmlApplicationContext("/data/gateway/java/src/main/resources/beans.xml");
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
System.out.println("------Records Creation--------" );
studentJDBCTemplate.create("Zara", 11);
studentJDBCTemplate.create("Nuha", 2);
studentJDBCTemplate.create("Ayan", 15);
System.out.println("------Listing Multiple Records--------" );
List<Student> students = studentJDBCTemplate.listStudents();
for (Student record : students) {
System.out.print("ID : " + record.getId() );
System.out.print(", Name : " + record.getName() );
System.out.println(", Age : " + record.getAge());
}
System.out.println("----Updating Record with ID = 2 -----" );
studentJDBCTemplate.update(2, 20);
System.out.println("----Listing Record with ID = 2 -----" );
Student student = studentJDBCTemplate.getStudent(2);
System.out.print("ID : " + student.getId() );
System.out.print(", Name : " + student.getName() );
System.out.println(", Age : " + student.getAge());
}
}
[root@d java]# java -jar /data/gateway/java/target/HelloSpringJDBCMysql-0.0.1-SNAPSHOT-jar-with-dependencies.jar
Dec 03, 2018 3:11:06 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@133314b: startup date [Mon Dec 03 15:11:06 CST 2018]; root of context hierarchy
Dec 03, 2018 3:11:06 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
------Records Creation--------
Created Record Name = Zara Age = 11
Created Record Name = Nuha Age = 2
Created Record Name = Ayan Age = 15
------Listing Multiple Records--------
ID : 1, Name : Zara, Age : 11
ID : 2, Name : Nuha, Age : 2
ID : 3, Name : Ayan, Age : 15
----Updating Record with ID = 2 -----
Updated Record with ID = 2
----Listing Record with ID = 2 -----
ID : 2, Name : Nuha, Age : 20
[root@d java]#
今天关于JDBC 获取 Oracle 数据库连接和使用 Driver的介绍到此结束,谢谢您的阅读,有关2. 通过原始的 Driver 接口通过读取 Properties 属性文件获取 JDBC 数据库连接 Connection、Caused by: java.lang.RuntimeException: Driver com.mysql.jdbc.Driver claims to not accept jdbcUrl, jd、ClassCastException:无法将oracle.jdbc.driver.T4CConnection强制转换为oracle.jdbc.OracleConnection、com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver等更多相关知识的信息可以在本站进行查询。
本文标签: