使用my exclipse对数据库进行操作(2)

时间:2021-09-04 07:53:12

二、增加

public static void main(String[] args) {
  //TODO Auto-generated method stub

//4.用户输入需要添加的项目
     Scanner sc = new Scanner(System.in);
     System.out.println("请输入你要添加的数据:");
     System.out.println("2.姓名");
     String two = sc.nextLine();
     System.out.println("3.性别");
     String three = sc.nextLine();
     System.out.println("4.年龄");
     int fore= Integer.parseInt(sc.nextLine());
     System.out.println("5.学校编码");
     int five= Integer.parseInt(sc.nextLine());

try {     

//1.导入数据库并且链接

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");     

Connection conn = DriverManager.getConnection("jdbc:sqlserver://192.168.8.60;DataBaseName=School","sa","123456");  

//3.写SQL语句  

 String sql= "insert into [Student] values(?,?,?,?)";  

//2.取出数据库内容并以SQL形式展现  

 PreparedStatement stmt= conn.prepareStatement(sql);

       stmt.setObject(1,two); 

       stmt.setObject(2,three); 

       stmt.setObject(3,fore); 

       stmt.setObject(4,five);

//5.判断是否添加成功

    if(!stmt.execute()){     

   System.out.println("数据添加成功");     

}else{     

 System.out.println("数据添加没成功");    

 }    

//6.关闭数据   

 if(!stmt.isClosed()){      stmt.close();     }     if(!conn.isClosed()){      conn.close();     }

   } catch (ClassNotFoundException e1) {     // TODO Auto-generated catch block     e1.printStackTrace();    }catch (SQLException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }                   }