JDBC 插入数据练习

package come.hanqi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class test3 {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入type:");
        int type = sc.nextInt();
        System.out.println("请输入IDCard:");
        String IDCard = sc.next();
        System.out.println("请输入ExamCard:");
        String ExamCard = sc.next();
        System.out.println("请输入StudentName:");
        String StudentName = sc.next();
        System.out.println("请输入Location:");
        String Location = sc.next();
        System.out.println("请输入Grade:");
        int Grade = sc.nextInt();
        
        
        Connection conn = null;
        
        try
        {
            Class.forName("oracle.jdbc.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
            conn = DriverManager.getConnection(url, "test1", "574004");
            
            System.out.println("连接数据库成功");
            
            // 第一种方法
            //Statement st = conn.createStatement();
            
            //int i = st.executeUpdate("insert into examstudent values (exam.nextval,"+type+",'"+IDCard+"','"+ExamCard+"','"+StudentName+"','"+Location+"',"+Grade+")");
            
            
            // 第二种方法
            PreparedStatement  ps = conn .prepareStatement("insert into examstudent values (exam.nextval,?,?,?,?,?,?)");
            
            ps.setInt(1, type);
            ps.setString(2, IDCard);
            ps.setString(3,ExamCard);
            ps.setString(4,StudentName);
            ps.setString(5,Location);
            ps.setInt(6,Grade);
            ps.executeUpdate();
            
            System.out.println("录入成功");
        }
            
            
//            if(i>0)
//            {
//                System.out.println("成功录入了"+i+"条信息");
//            }
//            else
//            {
//                System.out.println("操作无效");
//            }
//            st.close();
//        } 
//        
        
        catch (Exception e)
        {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            System.out.println("连接数据库失败");
        }
        finally 
        {
            if(conn!=null)
            {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            }
        }
        

    }

}

 

posted @ 2016-06-21 13:58  ╄承诺、带给的伤痛—  阅读(553)  评论(0编辑  收藏  举报