Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package escola;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.Scanner;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author 1189436
- */
- public class Escola {
- /**
- * @param args the command line arguments
- */
- public static int menu() {
- Scanner in = new Scanner(System.in);
- System.out.println("Digite a opção:");
- System.out.println("1 - Cadastrar aluno\n2 - Listar alunos\n0 - Sair\n");
- System.out.print("Opção: ");
- return in.nextInt();
- }
- public static void cadastrarAluno(Connection con) {
- String sql = "insert into Alunos values (?, ?, ?, ?, ?)";
- Scanner in = new Scanner(System.in);
- try {
- PreparedStatement ps = con.prepareStatement(sql);
- System.out.print("CPF: ");
- ps.setString(1, in.nextLine());
- System.out.print("Nome: ");
- ps.setString(2, in.nextLine());
- System.out.print("Matricula: ");
- ps.setString(3, in.nextLine());
- System.out.print("Idade: ");
- ps.setInt(4, in.nextInt());
- System.out.print("Sexo: ");
- String sexo = in.next();
- if ("m".equals(sexo) || "M".equals(sexo) || "masculino".equals(sexo)) {
- ps.setBoolean(5, true);
- } else {
- ps.setBoolean(5, false);
- }
- ps.executeUpdate();
- } catch (SQLException ex) {
- Logger.getLogger(Escola.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public static void listarAlunos(Connection con) {
- String sql = "select * from Alunos";
- try {
- ResultSet rs = con.createStatement().executeQuery(sql);
- while (rs.next()) {
- System.out.print(rs.getString("nome"));
- if (rs.getBoolean("sexo")) {
- System.out.println(" eh um homem");
- } else {
- System.out.println(" eh uma mulher");
- }
- }
- } catch (SQLException ex) {
- Logger.getLogger(Escola.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- public static void main(String[] args) {
- try {
- Class.forName("com.mysql.jdbc.Driver");
- String url = "jdbc:mysql://localhost/Escola";
- String user = "root";
- String pass = "macau@2015";
- Connection con = DriverManager.getConnection(url, user, pass);
- int opcao = menu();
- if (opcao == 1) {
- cadastrarAluno(con);
- } else if (opcao == 2) {
- listarAlunos(con);
- } else if (opcao == 0) {
- System.exit(0);
- }
- } catch (ClassNotFoundException ex) {
- Logger.getLogger(Escola.class.getName()).log(Level.SEVERE, null, ex);
- } catch (SQLException ex) {
- Logger.getLogger(Escola.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement