Is it possible to store user inputs by Scanner Class in a database?

1

IhaveanapplicationmadeinJava,andIneedtostoretheuser'scadastralinformationinthedatabase:

cpf,password,name,address,phone

System.out.println("Digite seu CPF");
cpf = ler.nextLine();           

System.out.println("Senha: ");
senha = ler.nextLine();

System.out.print("Nome Completo: ");
nome = ler.nextLine();

System.out.print("Endereço: ");
endereco = ler.nextLine();

System.out.print("Telefone: ");
telefone = ler.nextInt();

I want to get this data through the Scanner class and save it to the database.

To manage the database I'm using PostgresSQL, and the IDE for the application is Eclipse.

I've done the database connection with Eclipse through JDBC, but I'm not sure how I get the user inputs and I store it in the Database using the Java Scanner Class. I researched the internet and the only tutorials I encounter is using Jframe and IDE is NetBeans.

//Conexão do eclipse com o postgresql


import java.sql.*;
public class ConexaoSQL {

    //Statement = Realizar pesquisa no banco de dados
    public Statement stm;
    //ResulSet = Armazenar o resultado da pesquisa
    public ResultSet rs;

    //Driver = identifica no serviço do banco de dados
    private String driver = "org.postgresql.Driver";;

    //Caminho = Indica qual o diretório do banco de dados
    private String caminho = "jdbc:postgresql://localhost:5432/agencia";;

    /*
     Usuário: postgres
     Senha: admin
     */
    private String usuario = "postgres";;
    private String senha = "admin";;

    //Conection = Realizar a Conexão com banco de Dados
    public Connection con;

    public void conexao(){ //conecta ao banco de dados
        System.setProperty("jdbc.Drivers", driver);
        try {
            con=DriverManager.getConnection(caminho, usuario, senha);
            System.out.println("Conectado com Sucesso ao SQL!");
        } catch (SQLException e) {
            System.err.println("Erro de conexão ao SQL");
            e.printStackTrace();
        }
    }
    public void desconecta(){//desconecta do banco de dados
        try {
            con.close();
            System.out.println("Desconectado com Sucesso!");
        } catch (SQLException e) {
            System.err.println("Erro ao fechar conexão com banco de dados");
            e.printStackTrace();
        }

    }
}

Could anyone help me or send a tutorial that has something similar? Thanks in advance for any help.

      Table PostGreSQL
    
asked by anonymous 29.06.2016 / 16:07

2 answers

2

If you already have all the correct information in the variables (If there were no inconveniences using the Scanner object) then you can save to the bank using a PreparedStatement object

It would look something like this:

//...
ConexaoSQL conexao = new ConexaoSQL();
conexao.conexao();
Connection = conexao.con;
PreparedStatement statement = null;
StringBuilder sb = new StringBuilder();
try{
   sb.append("insert into Cliente values (?, ?, ?, ?, ?)");
   statement = con.preparedStatement(sb.toString());
   statement.setString(1, cpf);
   statement.setString(2, senha);
   statement.setString(3, nome);
   statement.setString(4, endereco);
   statement.setString(5, telefone);
   statement.execute();
   con.commit();
}catch(Exception e){
   System.out.println("Alguma exceção ocorreu" + e.toString());
}

You need to adjust according to your requirements. But basically you use a PreparedStatement object to insert that data into your table. Note that I used String in all fields, but if the data type of your field is different, you should adjust it according to the data type of the database.

Any questions, I'm available.

    
29.06.2016 / 17:15
1

You can create an object of type User and fill it with the information that comes from Scanner , it can be in the constructor itself of the user class itself or by the set methods of the class. And then create a method to insert into the database passing this object as a method parameter.

Ex:

public void inserirUsuario(Usuario usuario){
 //código para inserir no banco, tem vários exemplo de insert na internet
}
    
29.06.2016 / 17:18