Database mysql hashing passwords - java

so I'm trying to hash some passwords from a database from a login form and when I try first time to login it works with the password from database then I hash it with MD5 then when I come back to the login page I want to put the previously used password to log me in but it changed to the MD5 one. Is there any solution to have the MD5 one in the database and me to login with the first used?Thanks in advance (smecher.j is a variable who is 0)
public void validateLogin(){
DatabaseConnection connectNow = new DatabaseConnection();
DatabaseConnection connectNow2 = new DatabaseConnection();
Connection connectDB = connectNow.getConnection();
Connection connectDB2 = connectNow2.getConnection();
String verifyLogin = " SELECT count(1) FROM user_account WHERE username = '" + usernameTextField.getText() + "' AND password ='" + enterPasswordField.getText() +"'";
String insertFields3 = " UPDATE user_account SET password = MD5(password) WHERE username = '" + usernameTextField.getText() +"'";
try{
Statement statement = connectDB.createStatement();
Statement statement2 = connectDB2.createStatement();
ResultSet queryResult = statement.executeQuery(verifyLogin);
while(queryResult.next()){
if(queryResult.getInt(1)==1){
login1();
if(smecher.j==0) {
statement2.executeUpdate(insertFields3);
smecher.j++;
}
text1=enterPasswordField.getText();
}else{
loginMessageLabel.setText("Invalid login, please try again");
}
}
lol();
}catch(Exception e){
e.printStackTrace();
e.getCause();
}
}
public static String text1 = "";
public void lol() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String dbUrl = "jdbc:mysql://localhost:3306/databaselol?autoReconnect=true&useSSL=false";
String dbUsr = "root";
String dbPass = "!Iloriana12";
try {
String sql = "SELECT password FROM user_account where username = '" + usernameTextField.getText() + "'";
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(dbUrl, dbUsr, dbPass);
st = conn.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
String value = rs.getString("password");
text1 =value;
}
System.out.println(text1);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

when saving password you should save it encrypted and when you verify the password you should verify comparing the encrypted versions of the password as in.
String verifyLogin = " SELECT count(1) FROM user_account WHERE username = '" + usernameTextField.getText() + "' AND password =MD5('" + enterPasswordField.getText() +"')";
String insertFields3 = " UPDATE user_account SET password = MD5('" + enterPasswordField.getText() + "') WHERE username = '" + usernameTextField.getText() +"'";

Related

having trouble inserting values into table with syntax error

Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();

Java JDBC SQLite database locked by a select with where clause

I'm calling this method:
ArrayList<String> selectFilteredJump(String owner, String fromDate, String toDate, String env) {
ArrayList<String> a = new ArrayList<>();
Connection c;
Statement stmt;
StringBuilder whereClause = new StringBuilder("WHERE a.Date BETWEEN '"+fromDate+ "' and '" + toDate+"'");
if (!env.equals(constants.EMPTY) ) {
whereClause.append(" and a.Environment = '").append(env).append("'");
}
if (!owner.equals(constants.EMPTY) ) {
whereClause.append(" and a.UserId = '").append(owner).append("'");
}
String sql = "SELECT a.TicketID, a.Subject, a.UserID, a.Date, a.Solution, a.Comments," +
"a.Environment, (SELECT UserName FROM Users WHERE UserID = a.UserID) AS UserName FROM Tickets a " +
whereClause + " order by 4 asc;";
System.out.println(sql);
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName) ;
c.setAutoCommit(false);
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
a.add(rs.getString("TicketID"));
a.add(rs.getString("Subject"));
a.add(rs.getString("UserID"));
a.add(rs.getString("Date"));
a.add(rs.getString("Solution"));
a.add(rs.getString("Comments"));
a.add(rs.getString("Environment"));
a.add(rs.getString("UserName"));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return a;
}
Everything executes correctly but it seems that my database remains locked with no visible reason.
On the other side if I'm replacing with this method the database is ok after executing it:
ArrayList<String> selectAllJump() {
if (constants.DEBUG_MODE) System.out.println("selectAllJump");
ArrayList<String> a = new ArrayList<>();
Connection c;
Statement stmt;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName);
c.setAutoCommit(false);
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a.TicketID, a.Subject, a.UserID, a.Date, a.Solution, a.Comments," +
"a.Environment, (SELECT UserName FROM Users WHERE UserID = a.UserID) AS UserName FROM Tickets a " +
"order by 4 asc;");
while (rs.next()) {
a.add(rs.getString("TicketID"));
a.add(rs.getString("Subject"));
a.add(rs.getString("UserID"));
a.add(rs.getString("Date"));
a.add(rs.getString("Solution"));
a.add(rs.getString("Comments"));
a.add(rs.getString("Environment"));
a.add(rs.getString("UserName"));
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return a;
}
I've also tried to open the connection using specific configuration (like this):
c = DriverManager.getConnection("jdbc:sqlite:" + this.dbPath + this.dbName,setConfig().toProperties()) ;
private SQLiteConfig setConfig() {
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
config.setTempStore(SQLiteConfig.TempStore.MEMORY);
config.setCacheSize(1000);
config.setReadOnly(true);
return config;
}
and still the same error:
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
Any idea is welcomed.
Thank you.

Batch select and insert in Java

Hellos,
Can anyone help me look at this code; its generating an error."java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1"
//Code
private void btnBatchPayrollActionPerformed(java.awt.event.ActionEvent evt) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "arrowsdb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try{
Object newInstance = Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
Statement st = conn.createStatement();
// int rows = st.executeUpdate("INSERT INTO employeeinfo SELECT * FROM employeeinfo");
//int rows = st.executeUpdate("INSERT INTO payroll(employeeid,fname,basic,housing,transport,medical) SELECT * FROM employeeinfo('EmployeeId','Name,Basic','Housing','Transport','Medical')");
//INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;
int rows = st.executeUpdate("INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;)");
if (rows == 0) {
System.out.println("Don't add any row!");
} else {
System.out.println(rows + " row(s)affected.");
conn.close();
}
}
catch(ClassNotFoundException | SQLException e)
{
System.out.println(e);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(BatchPayroll.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thx
fm
You had an extra right parenthesis in your SQL. I haven't tested this, because I don't have these SQL tables, but I think this is correct. I used the MySQL 8 documentation to verify the format.
It also helps to format your code and SQL, so it's easier to spot errors like unbalanced parenthesis.
private void btnBatchPayrollActionPerformed(java.awt.event.ActionEvent evt) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "arrowsdb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Object newInstance = Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
Statement st = conn.createStatement();
// int rows = st.executeUpdate("INSERT INTO employeeinfo SELECT * FROM
// employeeinfo");
// int rows = st.executeUpdate("INSERT INTO
// payroll(employeeid,fname,basic,housing,transport,medical) SELECT * FROM
// employeeinfo('EmployeeId','Name,Basic','Housing','Transport','Medical')");
// INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT
// EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;
int rows = st.executeUpdate(
"INSERT INTO payroll " +
" (employeeid, fname, basic, housing, transport, medical) " +
"SELECT EmployeeId, Name, Basic, Housing, Transport, Medical " +
"FROM employeeinfo; ");
if (rows == 0) {
System.out.println("Don't add any row!");
} else {
System.out.println(rows + " row(s)affected.");
conn.close();
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(BatchPayroll.class.getName()).log(Level.SEVERE, null, ex);
}

Java sql Data pulling in the columnName but not the data

On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this
For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}

Inserting records into a MySQL table using Java

I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

Categories

Resources