用JDBC,Java连接MySQL并使用prepareStatement

//Author: ScottChiang
//Date: August 2012
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestPreparedStatement {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args){
        // TODO Auto-generated method stub
        if(args.length != 3){
            System.out.println("parameters error, do it again");
            System.exit(-1);
        }
        int deptno = 0;
        String dname = args[1];
        String loc = args[2];
        try{
            deptno = Integer.parseInt(args[0]);
        }catch (NumberFormatException e) {
            // TODO: handle exception
            System.out.println("Parameter error: deptno should be number format");
            System.exit(-1);
        }
        String url = "jdbc:mysql://localhost:3306/test";
        String user= "root";
        String password= "123456";
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            
            pstmt = conn.prepareStatement("insert into dept2 values (?,?,?)");
            pstmt.setInt(1, deptno);
            pstmt.setString(2, dname);
            pstmt.setString(3, loc);
            pstmt.executeUpdate();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try{

                if(pstmt != null){
                    pstmt.close();
                    pstmt = null;
                }
                if(conn != null){
                    conn.close();
                    conn = null;
                }
            }catch (Exception e) {
                // TODO: handle exception
                throw new RuntimeException(e);
            }    
        }
    }

}

 

posted @ 2013-04-14 06:21  ScottChiang  阅读(792)  评论(0)    收藏  举报