Passing a variable in MySQL statement - java

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.

Related

How to get last auto increment value in mysql table?

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?

When using JDBC connector and trying to insert into SQL database, nothing is added when I check the database

public sqlconnection()
{
try
{
Connection myConn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/userlogin","jeddy","admin");
insertIntoDB();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void insertIntoDB() throws SQLException
{
try
{
String driver ="com.mysql.jdbc.Driver";
Class.forName(driver);
String inpUsername=console.readLine("Enter username: ");
String inpPassword=console.readLine("Enter password: ");
String sql = ("insert into user(username, password) values('"+inpUsername+"', '"+inpPassword+"')");
PreparedStatement pStmt = myConn.prepareStatement(sql);
pStmt.executeUpdate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
The console readLine method simply stores the input from the user into variable. I am trying to insert these variable (inpUsername, inpPassword) into my SQL database. After running the code and entering the inputs, I go into MySql command line client and type select * from user and it returns Empty set(0.00 sec)

why this code on error still con.commit()

I have set the stdImage to not null in database, when i don't insert the image it throws an error but still con.commit() work out and data instead of rollback() save to database without image can someone solve the logical error in this code please. Actually rollback() is not working. I will be thankful.
public void stdSave(String stdID, String stdName, String fName, String sSec, String contactNo, Date bdate, String address, byte[] image) throws RemoteException, SQLException {
String stdQuery = "INSERT INTO dbo.StudentTable (stID, stName, stFName, classSection,"
+ "contact, date, pAddress) VALUES (?, ?, ?, ?, ?, ?, ?)";
String imgQuery = "INSERT INTO dbo.StdImage (stdID, stdImage) VALUES (?, ?)";
Savepoint save = null;
try {
try(PreparedStatement stmt = con.prepareStatement(stdQuery);
PreparedStatement stmt1 = con.prepareStatement(imgQuery)) {
con.setAutoCommit(false);
save = con.setSavepoint();
stmt.setString(1, stdID);
stmt.setString(2, stdName);
stmt.setString(3, fName);
stmt.setString(4, sSec);
stmt.setString(5, contactNo);
stmt.setDate(6, bdate);
stmt.setString(7, address);
stmt.execute();
stmt1.setString(1, stdID);
stmt1.setBytes(2, image);
stmt1.execute();
}
}
catch(Exception e) {
try {
con.rollback(save);
}
catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "Cannot add the student to database " + e);
}
}
con.commit();
}
You are calling con.commit(); after the try-catch block, and since your catch all the exceptions, you always calls commit.
You should probably move the commit inside the try block:
...
con.commit();
}
catch(Exception e) {
try {
con.rollback(save);
}
catch (Exception e1) {
JOptionPane.showConfirmDialog(null, "Cannot add the student to database " + e);
}
}
Never do con.commit() in catch block, this can lead to unintended commits. Move con.commit() to your try block.
Next, please see that you are doing rollback to a savepoint, but savepoint is null. It is not initialzed.
con.rollback(save); is done but here save=null.
Either simply do con.rollback() or initialialize the savepoint and then rollback upto it.

JDBC Update query error

I can't execute the update query on JDBC with where clause. I want to execute the query by concatenating some variables.
protected void updateEmail(String Email, String Username) {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "");
String query = "update access set email=" + Email + " where username=" + Username;
Statement st = conn.createStatement();
st.executeUpdate(query);
} catch (SQLException ex) {
System.out.println(ex);
} finally {
try {
conn.close();
} catch (SQLException ex) {
}
}
}
It says:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'bhusal1' in 'where clause'
String should be between two quotes 'name' instead of your way you have to use PreparedStatement instead to avoid syntax error or SQL Injection :
String query = "update access set email=? where username=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.executeUpdate();
This is most likely a problem with concatenation of the request. The approach you use is extremely bad and can cause any problems (including security).
To avoid problems, use PrepareStatement when you need to submit sql query parameters.
Here's an example that should solve your problem:
void updateEmail(String email,String username) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/project", "root", "")) {
String query = "update access set email = ? where username = ?";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, email);
statement.setString(2, username);
statement.executeUpdate();
}
}
catch (SQLException e) {
System.out.println(e);
}
}
You should put your variables email and username between quotes in the where clause to be able to do the update query

PreparedStatement is undefined error in jsp page

I am new to jsp pages and trying to make a login page by checking username and password from the database. Here is the code:
protected void CheckUser(String username, String password)
{
try {
connect();
PreparedStatement preparedStatement = con.PreparedStatement(
"SELECT * Users WHERE username = ? AND password = ?");
preparedStatement.setString(1,username);
preparedStatement.setString(2,password);
ResultSet rs = (ResultSet) preparedStatement.executeQuery();
} catch (Exception e) {
System.out.println("cannot connect");
e.printStackTrace();
}
}
I get the following error for con.PreparedStatement
The method PreparedStatement(String) is undefined for the type Connection
Can anyone help me with this?
Thanks
Edit: Here is my connection function:
static String dbUrl="jdbc:mysql://localhost:3306/Bank";
static String username="root";
static String password="";
static Connection con=null;
public static void connect ()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=(Connection) DriverManager.getConnection(dbUrl,username,password);
System.out.println("Connected!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("not connected");
}
}
You spelled the method wrong Connection#prepareStatement(String sql) throws SQLException.
It should be con.prepareStatement, not con.PreparedStatement.
You have to create a Prepared Statement by doing PreparedStatement preparedStatement = con.prepareStatement("your Query");
You need the from keyword in your Query.
Hence, your code should look like
PreparedStatement preparedStatement = con.prepareStatement("SELECT * from Users WHERE username = ? AND password = ?");
Not sure about other stuff, but your query is wrong considering its not an typo, will throw SQLException.
It should be
"SELECT * FROM Users WHERE username = ? AND password = ?"
^^^^
||||
here

Categories