Home Database Mysql Tutorial mysql存储过程学习及java调用存储过程

mysql存储过程学习及java调用存储过程

Jun 07, 2016 pm 03:02 PM
java mysql storage study transfer process

存储过程虽然经常听到,但是我遇到的项目还没有使用过,比较郁闷,只能选择自己入门了,也顺便与大家分享,希望大家也能如愿,呵呵。 首先我用的环境是window xpmysql5,这个大家应该都有的,没有的安装一下吧。好装好了,不要忘记将mysql.exe的路径目录放入

存储过程虽然经常听到,但是我遇到的项目还没有使用过,比较郁闷,只能选择自己入门了,也顺便与大家分享,希望大家也能如愿,呵呵。

首先我用的环境是window xp+mysql5,这个大家应该都有的,没有的安装一下吧。好装好了,不要忘记将mysql.exe的路径目录放入环境变量path中,这样在cmd里输入以下命令就可以进入mysql的命令行模式:mysql -u root -p  -> mysql密码即可。

mysql> delimiter //
mysql> create procedure hello()
    -> begin
    -> select 'It is not a HelloWorld';
    -> end
    -> //
Query OK, 0 rows affected (0.01 sec)
Copy after login

delimiter // 是将结束符由默认的;换成了//,如果不这样select......语句就会导致上面的代码出错,不信你可以试一下哈,呵呵。接着在mysql中查询上面的过程hello():

mysql> call hello()//
+------------------------+
| It is not a HelloWorld |
+------------------------+
| It is not a HelloWorld |
+------------------------+
1 row in set (0.00 sec)
Copy after login

我们再来一个好点的入门小实例吧
mysql> DROP TABLE IF EXISTS `userinfo`.`mapping`;
    -> CREATE TABLE  `userinfo`.`mapping` (
    ->   `cFieldID` smallint(5) unsigned NOT NULL,
    ->   `cFieldName` varchar(30) NOT NULL,
    ->   PRIMARY KEY  (`cFieldID`)
    -> ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    -> //
Query OK, 0 rows affected (0.14 sec)
Copy after login
想表中load值进空表  文件为:

filed.txt

1,MarketValue
2,P/L
3,EName
4,Nominal
5,Chg
Copy after login


mysql> load data infile 'd:\\field.txt' into table mapping
    -> fields terminated by ',' lines terminated by '\r\n' //
Query OK, 5 rows affected (0.02 sec)
Records: 5  Deleted: 0  Skipped: 0  Warnings: 0
mysql> select *from mapping//
+----------+-------------+
| cFieldID | cFieldName  |
+----------+-------------+
|        1 | MarketValue |
|        2 | P/L         |
|        3 | EName       |
|        4 | Nominal     |
|        5 | Chg         |
+----------+-------------+
5 rows in set (0.02 sec)
Copy after login
现在简历一个向mapping中插入一条记录并返回记录的总和

mysql> drop procedure if exists mappingProc;
    ->  create procedure mappingProc(out cnt int)
    ->  begin
    ->  declare maxid int;
    ->  select max(cFieldID)+1 into maxid from mapping;
    ->  insert into mapping(cFieldID,cFieldName) values(maxid,'hello');
    ->  select count(cFieldID) into cnt from mapping;
    ->  end
    ->  //
Copy after login
查找mappingProc():

mysql> call mappingProc(@a)//
mysql> select @a//
+------+
| @a   |
+------+
| 6    |
+------+
mysql> select * from mapping//
+----------+-------------+
| cFieldID | cFieldName  |
+----------+-------------+
|        1 | MarketValue |
|        2 | P/L                 |
|        3 | EName          |
|        4 | Nominal     |
|        5 | Chg         |
|        6 | hello       |
+----------+-------------+
Copy after login
下面是java代码用来调用MySQL的存储过程:

package kissJava.sql;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class SQLUtils {
    String url = "jdbc:mysql://127.0.0.1:3306/userInfo"; 
    String userName = "root";
    String password = "zhui007";
    public Connection getConnection() {
        Connection con=null;
        try{
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            con = DriverManager.getConnection(url, this.userName, this.password);
        }catch(SQLException sw){ 
         }
        return con;
    }
    public void testProc(){
        Connection conn = getConnection();
        CallableStatement stmt = null;
        try{
            stmt = conn.prepareCall("{call mappingProc(?)}");    
            stmt.registerOutParameter(1, Types.INTEGER);
            stmt.execute();
            int i= stmt.getInt(1);
            System.out.println("count = " + i);
        }catch(Exception e){
            System.out.println("hahad = "+e.toString());
        }finally{
            try {
                stmt.close();
                conn.close();
            }catch (Exception ex) {
                System.out.println("ex : "+ ex.getMessage());
            }
        }
    }
    public static void main(String[] args) {
        new SQLUtils().testProc();
    }
}
Copy after login


在到MySQL中查询可看到插入一条新的记录
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

See all articles