java special topic about JDBC
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
");
#2. Create the connection to the database
#
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:
@192.168.8.1:1521:yuewei","scott","tiger");
## 3.
Obtain an object that executes a sql statement based on the connection Statement stm = conn.CreatStatement();
ResultSet rs = stm.executeQuery(select * from dept);
rs.getString("deptno");
##JDBC connection database
•Create a program to connect to the database using JDBC, including
- 7
steps:
- 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),
-
This is achieved through the static method forName(String className) of the java.lang.Class class.
For example:
try{
//加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驱动程序类 ,加载驱动失败!"); e.printStackTrace() ; }
Copy after login成功加载后,会将Driver类的实例注册到DriverManager类中。
2、提供JDBC连接的URL
•连接URL定义了连接数据库时的协议、子协议、数据源标识。
•书写形式:协议:子协议:数据源标识
协议:在JDBC中总是以jdbc开始
子协议:是桥连接的驱动程序或是数据库管理系统名称。
数据源标识:标记找到数据库来源的地址与连接端口。
例如:(MySql的连接URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true:表示使用Unicode字符集。如果characterEncoding设置为
gb2312或GBK,本参数必须设置为true 。characterEncoding=gbk:字符编码方式。
3、创建数据库的连接
•要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象,
该对象就代表一个数据库的连接。
•使用DriverManager的getConnectin(String url , String username ,
String password )方法传入指定的欲连接的数据库的路径、数据库的用户名和
密码来获得。
例如:
//连接MySql数据库,用户名和密码都是root
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 login4、创建一个Statement
•要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3
种类型:
1、执行静态SQL语句。通常通过Statement实例实现。
2、执行动态SQL语句。通常通过PreparedStatement实例实现。
3、执行数据库存储过程。通常通过CallableStatement实例实现。
具体的实现方式:
Statement stmt = con.createStatement() ;
PreparedStatement pstmt = con.prepareStatement(sql) ;
CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
5、执行SQL语句
Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate
和execute
1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句
,返回一个结果集(ResultSet)对象。
2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或
DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等
3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的
语句。
具体实现的代码:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; int rows = stmt.executeUpdate("INSERT INTO ...") ; boolean flag = stmt.execute(String sql) ;
Copy after login6、处理结果
两种情况:
1、执行更新返回的是本次操作影响到的记录数。
2、执行查询返回的结果是一个ResultSet对象。
• ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些
行中数据的访问。
• 使用结果集(ResultSet)对象的访问方法获取数据:
while(rs.next()){ String name = rs.getString("name") ; String pass = rs.getString(1) ; // 此方法比较高效 }
Copy after login(列是从左到右编号的,并且从列1开始)
7、关闭JDBC对象
操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声
明顺序相反:
1、关闭记录集
2、关闭声明
3、关闭连接对象
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(); } } } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

typetraits are used in C for compile-time type checking and operation, improving code flexibility and type safety. 1) Type judgment is performed through std::is_integral and std::is_floating_point to achieve efficient type checking and output. 2) Use std::is_trivially_copyable to optimize vector copy and select different copy strategies according to the type. 3) Pay attention to compile-time decision-making, type safety, performance optimization and code complexity. Reasonable use of typetraits can greatly improve code quality.

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT

Renaming a database in MySQL requires indirect methods. The steps are as follows: 1. Create a new database; 2. Use mysqldump to export the old database; 3. Import the data into the new database; 4. Delete the old database.

Implementing singleton pattern in C can ensure that there is only one instance of the class through static member variables and static member functions. The specific steps include: 1. Use a private constructor and delete the copy constructor and assignment operator to prevent external direct instantiation. 2. Provide a global access point through the static method getInstance to ensure that only one instance is created. 3. For thread safety, double check lock mode can be used. 4. Use smart pointers such as std::shared_ptr to avoid memory leakage. 5. For high-performance requirements, static local variables can be implemented. It should be noted that singleton pattern can lead to abuse of global state, and it is recommended to use it with caution and consider alternatives.
