자바 preparestment 중복 사용 가능

2011 단어
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class MysqlTest {
	public static void main(String[] args) throws Exception {
		testPrepareStatement();
	}

	public static void testPrepareStatement() {
		Connection conn = getConnection();
		PreparedStatement ps = null;
		try {
			String sql = "delete from test";
			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
			close(ps);
			
			String insertStr = "insert into test(id,name) values(?,?)";
			ps = conn.prepareStatement(insertStr);
			ps.setInt(1, 1);
			ps.setString(2, "dandan");
			ps.execute();
			close(ps);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn);
		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
			conn = DriverManager.getConnection(url, "root", "test");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	//    Connection   Statement 
	public static void close(Connection conn,Statement st) {
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(st!=null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
        //    Connection 
	public static void close(Connection conn) {
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
        //    Statement 
	public static void close(Statement st) {
		if(st!=null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}

좋은 웹페이지 즐겨찾기