Statement 和 PreparedStatement ,CallabelStatement

package com.enhance.jdbc;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class PreparedStatementTest {
	private String driver;
	private String url;
	private String user;
	private String pass;
	private Statement stmt;
	private ResultSet rs;
	private PreparedStatement pstmt;
	public void initParam(String paramFile) throws Exception{
		Properties prop=new Properties();
		prop.load(new FileInputStream(paramFile));
		driver=prop.getProperty("driver");
		url=prop.getProperty("url");
		user=prop.getProperty("user");
		pass=prop.getProperty("pass");
	}
	public Connection getConnection() throws ClassNotFoundException, SQLException{
		Class.forName(driver);
		return DriverManager.getConnection(url,user,pass);
	}
	
	public void executeDmlAndDdlUseStmt()throws Exception{
		long start=System.currentTimeMillis();
		Connection conn=null;
		try {
			conn=getConnection();
			stmt=conn.createStatement();
			for (int i = 0; i < 1000; i++) {
				stmt.executeUpdate("insert into my_test (test_name)"
						+ " values('姓名"+i+"')");
			}
			System.out.println("使用Statement费时:"+(System.currentTimeMillis()-start));
			
		}finally{
			if(rs!=null)
				rs.close();
			if(stmt!=null)
				stmt.close();
			if(conn!=null)
				conn.close();
		}
		
		
	}
	
	public void executeDmlAndDdlUsePstmt()throws Exception{
		long start=System.currentTimeMillis();
		Connection conn=null;
		try {
			conn=getConnection();
			pstmt=conn.prepareStatement("insert into my_test (test_name) values(?)");
			
			for (int i = 0; i < 1000; i++) {
				pstmt.setString(1, "姓名2"+i);
				pstmt.executeUpdate();
			}
			System.out.println("使用PreparedStatement费时:"+(System.currentTimeMillis()-start));
			
		}finally{
			if(rs!=null)
				rs.close();
			if(pstmt!=null)
				pstmt.close();
			if(conn!=null)
				conn.close();
		}
		
		
	}
	
	/**
	 * 创建存储过程
	 * delimiter //
	 * create or replace procedure(a int,b int,out sum int)
	 * begin
	 * set sum=a+b;
	 * end;
	 * //
	 */
	public void callProcedure() throws Exception{
		try {
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			
			cstmt=conn.prepareCall("{call add_proc(?,?,?)}");
			cstmt.setInt(1, 4);
			cstmt.setInt(2, 5);
			//注册 输出参数
			cstmt.registerOutParameter(3, Types.INTEGER);
			cstmt.execute();
			System.out.println("执行结果是:"+cstmt.getInt(3));
			
		}finally{
			if(cstmt!=null)
				cstmt.close();
			if(conn!=null)
				conn.close();
		}
		
	}

	public static void main(String[] args) throws Exception{
		PreparedStatementTest pst=new PreparedStatementTest();
		pst.initParam("src/mysql.ini");
		pst.executeDmlAndDdlUseStmt();
		pst.executeDmlAndDdlUsePstmt();
	}
	
	
}

你可能感兴趣的:(statement)