其实,这篇短文,我早就应该写了。因为,java存储过程今后在各大数据库厂商中越来越流行,功能也越来越强大。这里以Oracle为例,介绍一下java存储过程的具体用法。 iihero on csdn) 一、如何创建java存储过程? 通常有三种方法来创建java存储过程。 1. 使用o
其实,这篇短文,我早就应该写了。因为,java存储过程今后在各大数据库厂商中越来越流行,功能也越来越强大。这里以Oracle为例,介绍一下java存储过程的具体用法。
iihero on csdn)
一、如何创建java存储过程?
通常有三种方法来创建java存储过程。
1. 使用oracle的sql语句来创建:
e.g. 使用create or replace and compile java source named "
后边跟上java源程序。要求类的方法必须是public static的,才能用于存储过程。
SQL> create or replace and compile java source named "javademo1"
2 as
3 import java.sql.*;
4 public class JavaDemo1
5 {
6 public static void main(String[] argv)
7 {
8 System.out.println("hello, java demo1");
9 }
10 }
11 /
Java 已创建。
SQL> show errors java source "javademo1"
没有错误。
SQL> create or replace procedure javademo1
2 as
3 language java name 'JavaDemo1.main(java.lang.String[])';
4 /
过程已创建。
SQL> set serveroutput on
SQL> call javademo1();
调用完成。
SQL> call dbms_java.set_output(5000);
调用完成。
SQL> call javademo1();
hello, java demo1
调用完成。
SQL> call javademo1();
hello, java demo1
调用完成。
2. 使用外部class文件来装载创建
e.g. 这里既然用到了外部文件,必然要将class文件放到oracle Server的某一目录下边。
public class OracleJavaProc
{
public static void main(String[] argv)
{
System.out.println("It's a Java Oracle procedure.");
}
}
SQL> grant create any directory to scott;
授权成功。
SQL> conn scott/tiger@iihero.oracledb
已连接。
SQL> create or replace directory test_dir as 'd:/oracle';
目录已创建。
SQL> create or replace java class using bfile(test_dir, 'OracleJavaProc.CLASS')
2 /
Java 已创建。
SQL> create or replace procedure testjavaproc as language java name 'OracleJavaProc.main(java.lang.String[])';
2 /
过程已创建。
SQL> call testjavaproc();
调用完成。
SQL> execute testjavaproc;
PL/SQL 过程已成功完成。
SQL> set serveroutput on size 5000
SQL> call dbms_java.set_output(5000);
调用完成。
SQL> execute testjavaproc;
It's a Java Oracle procedure.
3. 我推荐的一种方法,直接使用loadjava命令远程装载并创建。
先创建一个类, e.g.
import java.sql.*;
import oracle.jdbc.*;
public class OracleJavaProc ...{
//Add a salgrade to the database.
public static void addSalGrade(int grade, int losal, int hisal) ...{
System.out.println("Creating new salgrade for EMPLOYEE...");
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO salgrade " +
"(GRADE,LOSAL,HISAL) " +
"VALUES(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,grade);
pstmt.setInt(2,losal);
pstmt.setInt(3,hisal);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) ...{
System.err.println("ERROR! Adding Salgrade: "
+ e.getMessage());
}
}
}
使用loadjava命令将其装载到服务器端并编译:
D:eclipse3.1workspacedbtest>loadjava -u scott/tiger@iihero.oracledb -v -resolve Or
acleJavaProc.java
arguments: '-u' 'scott/tiger@iihero.oracledb '-v' '-resolve' 'OracleJavaProc.java'
creating : source OracleJavaProc
loading : source OracleJavaProc
resolving: source OracleJavaProc
查询一下状态:
连接到:
Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.1.0 - Production
SQL> SELECT object_name, object_type, status FROM user_objects WHERE object_type LIKE 'JAVA%';
OBJECT_NAME
--------------------------------------------------------------------------------
OBJECT_TYPE STATUS
------------------------------------ --------------
OracleJavaProc
JAVA CLASS VALID
OracleJavaProc
JAVA SOURCE VALID
测试一下存储过程:
SQL> create or replace procedure add_salgrade(id number, losal number, hisal num
ber) as language java name 'OracleJavaProc.addSalGrade(int, int, int)';
2 /
过程已创建。
SQL> set serveroutput on size 2000
SQL> call dbms_java.set_output(2000);
调用完成。
SQL> execute add_salgrade(6, 10000, 15000);
Creating new salgrade for EMPLOYEE...
PL/SQL 过程已成功完成。
SQL> select * from salgrade where grade=6;
GRADE LOSAL HISAL
---------- ---------- ----------
6 10000 15000
二、如何更新你已经编写的java存储过程?
假如要往类OracleJavaProc里添加一个存储过程方法,如何开发?
正确的步骤应该是先dropjava, 改程序,再loadjava。
e.g.修改OracleJavaProc类内容如下:
import java.sql.*;
import oracle.jdbc.*;
public class OracleJavaProc ...{
// Add a salgrade to the database.
public static void addSalGrade(int grade, int losal, int hisal) ...{
System.out.println("Creating new salgrade for EMPLOYEE...");
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql =
"INSERT INTO salgrade " +
"(GRADE,LOSAL,HISAL) " +
"VALUES(?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,grade);
pstmt.setInt(2,losal);
pstmt.setInt(3,hisal);
pstmt.executeUpdate();
pstmt.close();
}
catch(SQLException e) ...{
System.err.println("ERROR! Adding Salgrade: "
+ e.getMessage());
}
}
public static int getHiSal(int grade)
...{
try ...{
Connection conn =
DriverManager.getConnection("jdbc:default:connection:");
String sql = "SELECT hisal FROM salgrade WHERE grade = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);pstmt.setInt(1, grade);
ResultSet rset = pstmt.executeQuery();
int res = 0;
if (rset.next())
...{
res = rset.getInt(1);
}
rset.close();
return res;
} catch (SQLException e)
...{
System.err.println("ERROR! Querying Salgrade: "
+ e.getMessage());
return -1; }
}
}
如何更新呢?
D:eclipse3.1workspacedbtest>dropjava -u scott -v OracleJavaProc
D:/tiger@iihero.oracledbeclipse3.1workspacedbtest>loadjava -u scott -v -resolve Or
acleJavaProc/tiger@iihero.oracledb.java
arguments: '-u' 'scott/tiger@iihero.oracledb' '-v' '-resolve' 'OracleJavaProc.java'
creating : source OracleJavaProc
loading : source OracleJavaProc
resolving: source OracleJavaProc
后边的应用示例:
SQL> create or replace function query_hisal(grade number) return number as langu
age java name 'OracleJavaProc.getHiSal(int) return int';
2 /
函数已创建。
SQL> set serveroutput on size 2000
SQL> call dbms_java.set_output(2000);
调用完成。
SQL> select query_hisal(5) from dual;
QUERY_HISAL(5)
--------------
9999
全文完!
用法个人见解:不要手动drop java source, 不要手动drop procedure。

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

To monitor the health and performance of MySQL servers, you should pay attention to system health, performance metrics and query execution. 1) Monitor system health: Use top, htop or SHOWGLOBALSTATUS commands to view CPU, memory, disk I/O and network activities. 2) Track performance indicators: monitor key indicators such as query number per second, average query time and cache hit rate. 3) Ensure query execution optimization: Enable slow query logs, record and optimize queries whose execution time exceeds the set threshold.

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
