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

Asked

Viewed 362 times

1

inserir a descrição da imagem aquiI have an application made in Java, and I need to store the user’s registration information in the database:

Cpf, password, name, address, telephone

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 to the database.

To manage the database I am using Postgressql, and the IDE for the application is Eclipse.

I’ve already connected the database to Eclipse through JDBC, but I don’t know how to get user inputs and store them in the database using the Java Scanner Class. I searched the internet and the only tutorials I find is using Jframe and the 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 someone help me or send me a tutorial that has something similar? Thanks for any help.

      Table PostGreSQL
  • 2

    What have you done? Add the code of your form and your connection class to the question.

  • I added what I did at the time.

  • Alexandre your application is only in text mode?

  • Yes, text only, all information is printed on the console.

  • 2

    Young, it’s the same thing using Jframe or Scanner. Only changes where the data comes from.

  • Which columns have your table that want to save the data and which column type?

  • Table: Client Colum: Cpf password name address phone

  • @Alexandrevieiradesouza if all the information we have to keep asking separately or several times, it will be difficult to help you. All the questions I asked were very clear, but I have to ask you again to answer them. Read what was asked and try to answer as fully as possible.

  • @diegofm I’m sorry for the inconvenience, I’m new on the forum, I’m still learning how to use some of the features. I inserted an image of the table with the columns in the question, all the columns were created are of type Character Varying. The java application is only in text mode and all information will be printed in the console.

Show 4 more comments

2 answers

2

If you already have all the correct information in the variables (If no inconvenience occurred using the Scanner object) then you can save in the database using an object PreparedStatement

I’d be more or less 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());
}

It is necessary you adjust according to your requirements. But basically you use an object of PreparedStatement to insert this 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 according to the database data type.

Any questions, I’m available.

  • A silly question, why use Stringbuilder, instead of directly passing the query in prepareStatement?

  • 1

    Just custom. You can pass the query directly in preparedStatement smoothly. However, there will be cases where your query is not so well defined, for example, you will need to stop the string, add something dynamically, and write the string back, like "insert into " + Cliente.NOME_TABELA + " values (?,?,?,?,?)";. To avoid using this "+", always use Stringbuilder, it has higher performance.

  • The question of performance, I’ve read several debates about the use of various forms of string concatenation and the difference is very small, but in the matter of code organization, really is a good this way even.

  • The difference is small yes, I agree. But I always use Stringbuilder. Well, I’ve heard that the "+" calls a Stringbuffer implicitly, but I can’t say that.

  • Thanks @Andrewribeiro I will try to implement, if I get comment ;)

  • Hello @Andrewribeiro, I implemented what you sent, when running the application it appears Some exception occurred java.lang.Nullpointerexception All data declared in the database is as Character Varying and in the application as String. I don’t understand the reason for the mistake.

  • @Alexandrevieiradesouza, your application is trying to use a method of a null object. You should check which line is the error and try to understand which object is null. It may be the object con. Take a look and comment here again.

  • He himself @Andrewribeiro, I circled in debug mode and identified that it is con

  • Did you just copy and paste my code? I just noticed a little slip there. Instead of Connection = conexao.con;, use Connection con = conexao.con;. Identify why your object con within the Conexaosql class is giving null is outside the scope of this question. con within the Conexaosql class is not being initialized correctly. When this object works, the code will work.

  • 1

    @Andrewribeiro yes, I just copied and pasted. I’ll check what I can do from now on, thank you very much :)

Show 5 more comments

1

You can create an object of the User type and fill it with the information that comes from Scanner, can be in the constructor of the user class itself or by the methods set class. And then create a method to insert into the database by 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
}
  • 1

    Your answer does not represent, in fact, a solution to the problem presented.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.