How to get last auto increment value in mysql table? - java

I'm working on a javafx project where a user can register as either a driver or a client. For this, I created 3 tables in a mysql database, a general one for all users and 2 specific ones for the drivers and the clients. When a new user registers he is placed in the database_user table and, depending on his selected role, he is also placed in either database_client or database_driver. The problem is that the specific tables should have a column storing the primary key value (autoincrement value) from the general table, for easier communication.
public static void registerClient(ActionEvent event, String username, String password, String role, String name, int age, String gender, String email)
{
/*
these variables are the connections to the mysql database
*/
Connection connection = null;
PreparedStatement psInsert = null;
PreparedStatement psInsertClient = null;
PreparedStatement psCheckUserAlreadyExists = null;
//PreparedStatement psCheckEmailAlreadyUsed = null;
ResultSet resultSet = null;
try{
/*
this will attempt to establish a connection with the db
*/
connection = DriverManager.getConnection("jdbc:mariadb://lazarov.go.ro:3306/RideShare", "root", "chocolate");
psCheckUserAlreadyExists = connection.prepareStatement("SELECT * FROM database_user WHERE username = ?");
psCheckUserAlreadyExists.setString(1, username);
//psCheckEmailAlreadyUsed = connection.prepareStatement("SELECT * FROM user_database WHERE email = ? ");
//psCheckEmailAlreadyUsed.setString(7, email);
resultSet = psCheckUserAlreadyExists.executeQuery();
/*
check if the resultSet is empty
if true => username already taken => notify user about this
*/
if(resultSet.isBeforeFirst())
{
System.out.println("Username already taken!");
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("User already exists!");
alert.showAndWait();
}
else
{
psInsert = connection.prepareStatement("INSERT INTO database_user (username, password, role, name, age, gender, email) VALUES (?, ?, ?, ?, ?, ?, ?)");
psInsert.setString(1, username);
psInsert.setString(2, password);
psInsert.setString(3, role);
psInsert.setString(4, name);
psInsert.setInt(5, age);
psInsert.setString(6, gender);
psInsert.setString(7, email);
psInsert.executeUpdate();
ResultSet rs = null;
psInsert = connection.prepareStatement("SELECT max(user_id) FROM database_user");
rs = psInsert.executeQuery();
// driver specific
int userId = resultSet.getInt("max(user_id)"); // this is where the error occurs
//Connection connectionDriver = null;
psInsertClient = connection.prepareStatement("INSERT INTO database_client (user_id, ride_requested, location, destination, corresponding_driver_id) VALUES (?, ?, ?, ?, ?)");
psInsertClient.setInt(1, userId);
psInsertClient.setBoolean(2, false);
psInsertClient.setString(3, null);
psInsertClient.setString(4, null);
psInsertClient.setInt(5, 0);
changeScene(event, "client.fxml", "RideShare - Client", username, role, name, age, gender, email);
}
}catch (SQLException e)
{
e.printStackTrace();
}finally {
/*
close db connections to avoid memory leaks
*/
if(resultSet != null)
{
try{
resultSet.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psCheckUserAlreadyExists != null)
{
try{
psCheckUserAlreadyExists.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psInsert != null)
{
try {
psInsert.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(psInsertClient != null)
{
try {
psInsertClient.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
if(connection != null)
{
try{
connection.close();
}catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
If I try to create a new user, the user is added in the database_user correctly, but throws the error "wrong row position" when trying to store it in the "database_client" as well. How can I successfully get the last autoincremented value from the general table?

Related

How to run a main method in java after pressing a button in a jsp?

I'm new to this. I need to make a jsp to upload a CSV file and send the data in it to a mysql database. I made a code in Java to get the latter part done, but not sure how to connect it to the jsp, so when the user press uploads the java code runs.
My java code:
import java.io.*;
import java.sql.*;
public class dbInserter {
public static void main(String[] args) {
String jdbcURL = "jdbc:mysql://localhost:3306/testDb";
String username = "root";
String password = "1234";
String csvFilePath = "C:/Users/Name/Desktop/Attendance.csv";
int batchSize = 20;
Connection connection = null;
try {
connection = DriverManager.getConnection(jdbcURL, username, password);
connection.setAutoCommit(false);
String sql = "INSERT INTO csv (name, `in-time`, `out-time`) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
BufferedReader lineReader = new BufferedReader(new FileReader(csvFilePath));
String lineText = null;
int count = 0;
lineReader.readLine(); // skip header line
while ((lineText = lineReader.readLine()) != null) {
String[] data = lineText.split(",");
String name = data[0];
String inTime = data[1];
String outTime = data[2];
statement.setString(1, name);
statement.setString(2, inTime);
statement.setString(3, outTime);
statement.addBatch();
if (count % batchSize == 0) {
statement.executeBatch();
}
}
lineReader.close();
// execute the remaining queries
statement.executeBatch();
connection.commit();
connection.close();
} catch (IOException ex) {
System.err.println(ex);
} catch (SQLException ex) {
ex.printStackTrace();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
I tried using a servlet, but since I have very little experience using it, I ran into many errors. Would really appreciate it if someone can help me with this.

How to update timestamp column in PostgreSQL database?

I am trying to update PostgreSQL database column. I do not know how to parse and send it to the database which matches the data type? How do I do this?
Here is my Code:
#Override
public void updateTaskStatus(String applicationNo, String prevTask, String currTask, String taskStatus,
String user) {
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps2 = null;
PreparedStatement ps3 = null;
ResultSet rs = null;
java.util.Date date = new java.util.Date();
Timestamp timestamp = new Timestamp(date.getTime());
try {
conn = ConnectionManager.getConnection();
String query = "SELECT * " + "FROM public.nt_t_task_det " + "where tsd_app_no=? ;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNo);
rs = ps.executeQuery();
if (rs.next() == true) {
if (!(rs.getString("tsd_task_code").equals(currTask))) {
// insert to history table
String q = "INSERT INTO public.nt_h_task_his "
+ "(tsd_seq, tsd_vehicle_no, tsd_app_no, tsd_task_code, tsd_status, created_by, created_date) "
+ "VALUES(?, ?, ?, ?, ?, ?, ?); ";
ps2 = conn.prepareStatement(q);
ps2.setInt(1, rs.getInt("tsd_seq"));
ps2.setString(2, rs.getString("tsd_vehicle_no"));
ps2.setString(3, applicationNo);
ps2.setString(4, prevTask);
ps2.setString(5, taskStatus);
ps2.setString(6, rs.getString("created_by"));
ps2.setTimestamp(7, rs.getTimestamp("created_date"));
int i = ps2.executeUpdate();
conn.commit();
try {
if (ps2 != null)
ps2.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.commit();
if (i > 0) {
// update task details table
String q2 = "UPDATE public.nt_t_task_det "
+ "SET tsd_task_code=?, tsd_status='O', created_by=?, created_date=? "
+ "WHERE tsd_app_no=?";
ps3 = conn.prepareStatement(q2);
ps3.setString(1, currTask);
ps3.setString(2, applicationNo);
ps3.setString(3, user);
ps3.setTimestamp(4, timestamp);
ps3.executeUpdate();
conn.commit();
try {
if (ps3 != null)
ps3.close();
} catch (Exception e) {
e.printStackTrace();
}
String queueNumber = findQueueNumberFromApplicationNo(conn, applicationNo);
if (queueNumber != null && !queueNumber.isEmpty() && !queueNumber.trim().equalsIgnoreCase("")) {
updateQueueNumberTaskInQueueMaster(conn, queueNumber, currTask, "O");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (ps2 != null)
ps2.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the exception in my console:
org.postgresql.util.PSQLException: ERROR: column "created_date" is of
type timestamp without time zone but expression is of type character
varying
Hint: You will need to rewrite or cast the expression.
The parameters of the UPDATE statement don't match the arguments you are supplying.
The first argument is for the first ?, the second one for the second and so on. You got the order mixed up.

Why I am getting "oracle.jdbc.driver.OracleResultSetImpl#3ee82600" value in ResultSet instead Userid and password

I've the below DAO method:
public boolean validate(String UserName,String password) throws Exception
{
this.userName=UserName;
this.password=password;
boolean status=false;
PreparedStatement pst = null;
ResultSet rs = null;
Connection con = null;
DataBase db =new DataBase();
con=db.dbConnection();
User user=new User();
try {
pst=con.prepareStatement("select * from login where userId=? and password=?");
pst.setString(1, user.getUserName());
pst.setString(2, user.getPassword());
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
rs=pst.executeQuery();
System.out.println("Result in Resultset"+rs);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while(rs.next())
{
if((rs.getString("USERID")==user.getUserName()) && (rs.getString("Password")==user.getPassword()))
{
status=true;
}
else
{
status=false;
}
}
} catch (SQLException e) {
System.out.println("Data is not store in result set");
e.printStackTrace();
}
return status;
}
so here is the problem I am facing in the image I am getting this-"oracle.jdbc.driver.OracleResultSetImpl#3ee82600" value in ResultSet object rs, instead of userid and password from my database
You can get the values of Userid and password by doing
if(rs.next()) {
String userId = rs.getString("userId");
String password = rs.getString("password");
}

Soap Web Service- compare data entered against data from mysql database

I have a soap web service that is connected to mySQL database. It has two methods, one is insert() and the other is verify(). The first one enables the user to enter data such as name, email and password. It saves the records in the database successfully.
However am having problems with writing the verify method. It has as input parameters, email and password. It must compare the data entered with those stored in the database and return "registered" or "not registered" if it cant find the match in mysql database. Am having problem writing the codes. Could you please help, am new to jdbc and java web services. Am using netbeans.
Thanks a lot.
Here are my codes:
#WebMethod(operationName = "insert")
public String insert(#WebParam(name = "name") String name,
#WebParam(name = "email") String email,
#WebParam(name = "password") String password {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
PreparedStatement st = con.prepareStatement("insert into register values(?,?,?)");
st.setString(1, name);
st.setString(2, email);
st.setString(3, password);
st.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return "record inserted";
}
/**
* Web service operation
*/
#WebMethod(operationName = "Verify")
public String CheckUser(#WebParam(name = "email") String email,
#WebParam(name = "password") String password) {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
If
// problems to write this statement!!! I need to compare the username and password
// with some select * from register where password == #password and email == #email?
return "Registered user";
else
return "Not registered";
}
This example could work (you might have to change column names in the query). Also, you should close the connection in the insert method, in the same way that this example.
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "1234");
PreparedStatement st = con.prepareStatement("select 1 from register where password = ? and email = ? and name = ?");
st.setString(1, password);
st.setString(2, email);
st.setString(3, name);
ResultSet result = st.executeQuery();
if (result.next()) { //.next() returns true if there is a next row returned by the query.
return "Registered user";
} else {
return "Not registered";
}
} catch (Exception e) {
//TODO manage the exception.
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {}
}
}

Passing a variable in MySQL statement

I'm trying to record String variables into a database in a MySQL statement in Java.
I've read this and this but I couldn't succeed.
Here is my code:
public void registerUser( String userName, String password ) {
try {
String insertQuery = "INSERT INTO Credentials ('11', name, pass) VALUES('11', ?, ?)";
pstmt = connection.prepareStatement(insertQuery);
pstmt.setString(2, userName);
pstmt.setString(3, password);
pstmt.executeUpdate();
// statement.executeUpdate("INSERT INTO Credentials VALUES(3, 'userName', 'password')");
} catch (SQLException e) {
e.printStackTrace();
} finally {
// close the connection when done
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}//END finally
}//END registerUser
As can you see, this code is getting two String values and it should put them into the database. But I can't find the proper solution.
Any ideas?
Thanks.
This:
pstmt.setString(2, userName);
pstmt.setString(3, password);
Needs to be:
pstmt.setString(1, userName);
pstmt.setString(2, password);
You are only setting two variables in your PreparedStatement, so you need to start counting at 1. The integers used in the setter methods need to match up with the question marks in your statement, not the parameter list of the given SQL string.

Categories