Question

I am writing an access control program in Java that captures passwords using JPasswordField. Since the jpasswordfield.getPassword() method returns values as chars, I need to know how to save the char value in a MYSQL database using preparedstatement. I am using MYSQL fields password char[100] for storing the passwords.

Please help.

Was it helpful?

Solution

I made a simple example of storing a char array in a database using a prepared statement. I used Java DB instead of MySQL as it is included in the JDK (jdk1.7.0/db/lib/derby.jar) it shouldn't matter for this example.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class Example {
    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:derby:memory:sampleDB;create=true");
             Statement statement = connection.createStatement()
        ) {
            char[] pw = "password".toCharArray();
            statement.execute("create table sample(pw char(10))");

            try (ResultSet resultSet = statement.executeQuery("select * from sample");
                 PreparedStatement preparedStatement = connection.prepareStatement("insert into sample values (?)")
            ) {
                for (int i = 1; i <= 10; i++) {
                    preparedStatement.setString(1, new String(pw) + i);
                    preparedStatement.execute();                    
                }

                while (resultSet.next()) {
                    System.out.println(resultSet.getString(1));
                }
            }
        }
    }
}

As others already said, you should not store passwords in plaintext in the database. Instead you should store a hash of it (SHA-1 Hash in Java).

OTHER TIPS

use some password encryption algorithms to save password ,it would be good practice ,google it for details,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top