JDBC oracle update statements in java - java

Can someone tell me why this fails at the ps.excuteUpdate statement? It seems to work and changes the data in the database but it fails at the execute statement which won't let it execute the other two ps1 and ps2 statements.
buyStock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
BuyStock();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
public void BuyStock() throws SQLException, IOException{
Connection conn = null;
PreparedStatement ps = null;
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
int i = 0;
String username = UserLoginInfo.userEmail;
int bank = 75000;
String string1= "goog";
int shares = 25;
conn = ConnectionManager.getConnection();
if (i == 0) {
ps = conn.prepareStatement("UPDATE L1_Standings SET BANK = ? WHERE EMAIL = '" + username + "'");
ps1 = conn.prepareStatement("UPDATE L1_Stocks SET TICKER_SYMBOL = ? WHERE EMAIL = '" + username + "'");
ps2 = conn.prepareStatement("UPDATE L1_Stocks SET NUM_SHARES = ? WHERE EMAIL = '" + username + "'");
ps.setInt(1, bank);
ps1.setString(1, string1);
ps2.setInt(1, shares);
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
ps1.close();
ps2.close();
} else {
System.out.println("False");
}

Related

What is the right way to deal with the PreparedStatement in the Java program flow?

There are two methods in which the PreparedStatement is used.
The first method is called in the second method.
First method:
protected List<String> findResultsByMandantId(Long mandantId) {
List<String> resultIds = new ArrayList<>();
ResultSet rs;
String sql = "SELECT result_id FROM results WHERE mandant_id = ?";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.setLong(1, mandantId);
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
resultIds.add(rs.getString(1));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return resultIds;
}
Second method:
protected void findResultLineEntityToDelete(Long mandantId, String title, String context) {
List<String> resultIds = findResultsByMandantId(mandantId);
String [] resultIdsArr = resultIds.toArray(String[]::new);
ResultSet rs;
//String sql = "SELECT * FROM resultline WHERE result_id in (SELECT result_id FROM results WHERE mandant_id =" + mandantId + ")";
String sql = "SELECT * FROM resultline WHERE result_id in (" + String.join(", ", resultIdsArr)+ ")";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
if (rs.getString(3).equals(title) && rs.getString(4).equals(context)) {
System.out.println("Titel: " + rs.getString(3) + " " + "Context: " + rs.getString(4));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The class in which both methods are located extends the JDBCBaseManager.
JDBCBaseManager:
private final String url = "jdbc:mysql://localhost:3306/database";
private final String userName = "root";
private final String password = "";
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private int batchSize = 0;
public JDBCBaseManager() {
// Dotenv env = Dotenv.configure().directory("./serverless").load();
// url = env.get("DB_PROD_URL");
// userName = env.get("DB_USER");
// password = env.get("DB_PW");
}
public void getConnection() {
try {
if (connection == null) {
connection = DriverManager.getConnection(url, userName, password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
if (connection == null) {
getConnection();
}
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void startBatch(int batchSize) throws SQLException {
connection.setAutoCommit(false);
setBatchSize(batchSize);
}
public void commit() {
try {
if (connection != null && !connection.isClosed()) {
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
The ResultSet in the second method still contains the results from the first method.
I already tried to close the connection and open it again before the second method is executed, but then I get the errors:
java.sql.SQLException: No operations allowed after statement closed.
java.sql.SQLNonTransientConnectionException: No operations allowed
after connection closed.
Can you tell me how to deal with the statement correctly in this case? Is my BaseManager incorrectly structured?
Here lies the error
public JDBCBaseManager() {
private PreparedStatement preparedStatement = null;
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
......
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
You build the prepare statement only the first time the method getPreparedStatement is called because only the first time the field preparedStatement is null. Every next time you call the method getPreparedStatement you receive the previous preparedStatement from the previous SQL and not the new one.
Remove the check for if (preparedStatement == null) {
You need to build a new preparedStatement every time you want to execute a new SQL.

Database is locked in SQLite [Java]

updated
try
{
sqlite.setDbPath(dbPath);
con = sqlite.connect();
if(!con.isClosed())
{
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"'"; // and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
while(rs.next())
{
if(rs.getString("Username").equals(username))//confronto se Username รจ gia esistente
{
trovato = true;
risultato = "gia' presente";
}
}
if(trovato==false) {
createUsers(username,password,name,surname,email,appname,ip,authorized,token);
risultato="inserito";
}
if(con!=null)
{
con.close();
}
if(sqlite != null)
{
sqlite.close();
}
if(rs != null)
{
rs.close();
}
}
In try catch block I've open connection with database embedded but in first time i don't close all connection..
With if control the program close all open connection and works well
Update 2
Here is an abbreviated version using try-with-resource instead. Code is simpler and shorter
public String RegisterUser(... ) {
boolean trovato = false;
int authorized=0;
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"' and Password='"+password+"'";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();
Statement updStatement = con.createStatement();
) {
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
// handle result set as before
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
if(trovato==false) {
createUser(username, password, name, surname, appname, email, ip)
}
return "username: " + username;
}
private createUser(String username, String password, String name, String surname, String appname, String email, String ip {
String query1="INSERT INTO Apps (Username,Password,Name,Surname,Email,AppName,Ip,Authorized,Token) VALUES ('" + username + "'," + "'" +password +"','" + name + "','" + surname + "','" +email + "','" + appname + "','"+ip+"','"+authorized+"','"+token+"')";
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();) {
updStatement.executeUpdate(query1);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
}
It could very well be that your prepared statement isn't properly closed. Change
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
to
statement = con.createStatement();
ResultSet rsActiveServices = statement.executeQuery(query);
where statement is declared before try
java.sql.Connection con = null;
Statement statement = null;
and then close it in your finally clause
finally
{
try
{
statement.close();
con.close();
sqlite.close();
}
Update 1
I just noticed that your are trying to close your objects twice which is wrong, remove the first set of close calls and only close within finally {} at the end.
Resolved
I do errors with open and close connection in Main.. With SQLite the connection you have to open and close everytime it's carried out a query of all type(Insert, Delete,Update ecc..)

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

SQL Prepared Statement & returning type

I have just created a method in my class file, were I insert data into my sql database.
1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
Car c = new Car();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, aLicense);
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, aUsername);
preparedStmt.setString(4, aPassword);
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return c;
}
Calling the method returns an error that the method is not applicable for arguments
//int addingID = Integer.parseInt(enteringID.getText());
String addingReg = enteringReg.getText();
int addingJourneys = Integer.parseInt(enteringJourneys.getText());
String addingUsername = enteringUsername.getText();
#SuppressWarnings("deprecation")
String addingPassword = enteringPassword.getText();
Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
int addStatus = myCar.addVehicle(newCar);
if (addStatus == 1) {
JOptionPane.showMessageDialog(null, "Vehicle Added");
enteringID.setText("(eg. 1-999)");
enteringReg.setText("(eg. - 162-MH-749)");
enteringJourneys.setText("(eg. 7)");
enteringUsername.setText("(eg. - username#domain.com)");
enteringPassword.setText("");
}
else {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, "Error, Please Try Again");
}
}
});
This is not a final answer for your question, but purely to clarify my comment.
If you want your method to return a Car object, you'll have to create an instance of class Car and return it:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
statement = conn.createStatement();
String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString(1, "'" + aLicense + "'");
preparedStmt.setInt(2, aJourneys);
preparedStmt.setString(3, "'" + aUsername + "'");
preparedStmt.setString(4, "'" + aPassword + "'");
preparedStmt.execute();
conn.close();
Car c = new Car();
//Do anything with the car object that you like.
//for example: c.setColor("blue");
return c;
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
//kayaman is correct here: we still need to return something here in order to be able to compile
return null;
}
Separate the logic!
Use this class to retrieve connection where you need it:
public class DatabaseConnection
{
private static final String CONN_URL = "some connection url";
private static Connection instance = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static synchronized Connection getInstance() throws SQLException
{
if (instance == null)
{
instance = DriverManager.getConnection(CONN_URL);
}
return instance;
}
}
Use it in your function like this:
public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword)
{
String sql = "insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword) values (?, ?, ?, ?)";
try (Connection conn = DatabaseConnection.getInstance(); PreparedStatement prepStatement = conn.prepareStatement(sql))
{
Car successfulAdd = new Car();
prepStatement.setString(1, aLicense);
prepStatement.setInt(2, aJourneys);
prepStatement.setString(3, aUsername);
prepStatement.setString(4, aPassword);
if (prepStatement.execute())
{
return successfulAdd;
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}

Connect to MySQL on Android, Driver doesn't work

I want to connect to my MySQL server, but the driver doesn't work.
How can I fix this, or what am I doing wrong? Do I need to import extra libraries (I didn't do that)?
This is my code:
public void Connection() {
String retrievedUserName = "";
String retrievedPassword = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://domainexample.com", "username", "passwoord");
PreparedStatement statement = con.prepareStatement("SELECT * FROM Gebruiker WHERE users= '" + "username" + "'");
ResultSet result = statement.executeQuery();
while (result.next()) {
retrievedUserName = result.getString("gebruikersnaam");
retrievedPassword = result.getString("password");
}
System.out.println(retrievedUserName + " passwoord = " + retrievedPassword);
} catch (Exception e) {
e.printStackTrace();
}
}

Categories