I'm using these two methods in order to update the balance of a bank app I'm writing, but the database refuses to update and I'm not sure why.
Function for getting how much to add:
public void addIncome(String cardNum,Scanner scanner){
System.out.println("Enter income: ");
int income = scanner.nextInt();
scanner.nextLine();
dataBase.addBalance(income,cardNum);
}
Prepared statement and function for query:
private final String ADD_BALANCE = ("UPDATE card SET balance=balance+? WHERE number=?");
public void addBalance(int amount, String number){
try (Connection con = this.dataSource.getConnection();
final var sql = con.prepareStatement(ADD_BALANCE)){
sql.setInt(1, amount);
sql.setString(2,number);
sql.executeUpdate();
}catch (SQLException throwables) {
throwables.printStackTrace();
}
}
You're missing a call to commit, meaning the transaction will implicitly rollback when the connection is closed (at the end of the try).
try (Connection con = this.dataSource.getConnection();
final var sql = con.prepareStatement(ADD_BALANCE)) {
sql.setInt(1, amount);
sql.setString(2, number);
sql.executeUpdate();
con.commit(); // HERE
}
Related
I'm new to JDBC and using the following code to update the row using MySQL JDBC driver. I have no idea why executeUpdate() is not updating the content in the database.
import java.sql.*;
import java.util.*;
public class UpdateDb {
UpdateDb() throws Exception,SQLException{
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb","root","");
String q="update table inserttbl set Name=?, City=? where id=?";
System.out.print("Enter new name to update: ");
String n = sc.nextLine();
System.out.print("Enter new city name to update: ");
String c = sc.nextLine();
System.out.print("Enter previous id: ");
int id = sc.nextInt();
PreparedStatement ps = conn.prepareStatement(q);
ps.setString(1, n);
ps.setString(2, c);
ps.setInt(3, id);
ps.executeUpdate();
System.out.print("updated");
conn.close();
}
public static void main(String[] arg) {
try {
UpdateDb up = new UpdateDb();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Can anyone help me?
Your query string is wrong. It should be something like this:
String updateQuery = "UPDATE inserttbl SET Name=?, City=? WHERE id=?";
Look here for the proper syntax of update: https://www.mysqltutorial.org/mysql-jdbc-update
Also if you want to update then use an update table command. The command that you used for insert is wrong.
Also for error print out the exception that you logged.
this is my method for writing db query.
public static void post() throws Exception{
int clientMPNumber = Parcel.typeClientNumber();
int orderPassword = Parcel.generatePass();
try{
Connection con = ConnectionDB.getConnection();
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='77' AND `ClientPass`='1111';");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
I'm trying to do something like ATM machine. So I expect that user types his ID and password, and then the user can withdraw money or deposit money.
So I want to check login data correctness. User needs to type correct ID/password [logins/passwords are placed in MySQL DB].
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='USER TYPES IT' AND `ClientPass`='USER TYPES IT';");
There is a sentence: "USER TYPES IT", this is my problem. I want to use here a Scanner or something like this. How can I do it?
A prototype for you (just an example, you should split up the part get userid, password, outside of this function for better practice):
public void post (){
Scanner sc = new Scanner(System.in);
System.out.println ("please enter user id:");
String userId = sc.nextLine();
System.out.println("please enter password:");
String pass = sc.nextLine();
Connection con;
PreparedStatement posted;
try {
con = ConnectionDB.getConnection();
String sql = "UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`=? AND `ClientPass`=?";
posted = con.prepareStatement(sql);
posted.setString(1, userId);
posted.setString(2, pass);
posted.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
posted.close();
con.close();
}
}
i am trying to add two methods to withdraw and deposit money in Bank Class . My Database name is javatest . table name is bank and following is the code . Problem is that when i run this code compiler says You have an error in your SQL syntax; i did check code 3-4 times but really unable to get it please help me with it .
public static void main(String[] args)
{
Connection connection= null ;
Statement stmt = null ;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/javatest","root","");
stmt= connection.createStatement();
withdrawfromchecking(connection, stmt, new BigDecimal(100), 1);
Depositinsaving(connection, stmt, new BigDecimal(444), 1);
stmt.executeBatch();
System.out.println("Done");
}
catch (ClassNotFoundException e) {e.getMessage();}
catch (SQLException e) {e.printStackTrace();}
finally
{
if(connection!=null){try {connection.close();} catch (SQLException e) {e.printStackTrace();}}
if(stmt!=null){try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}
}
}
public static void withdrawfromchecking(Connection connection ,Statement stmt, BigDecimal amount , int id ) throws SQLException
{
stmt.addBatch("UPDATE bank SET checkingbalance = checkingbalance-"+amount+"WHERE id="+id);
}
public static void Depositinsaving(Connection connection ,Statement stmt, BigDecimal amount , int id ) throws SQLException
{
stmt.addBatch("UPDATE bank SET savingbalance = savingbalance+ "+amount+"WHERE id="+id);
}
}
Error comes for this line - stmt.executeBatch(); when i run program
EDIT : Exact error statement
java.sql.BatchUpdateException: 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 'id =1' at line 1 at
com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:1193) at
MyPackage.BankAccount.main(BankAccount.java:24)
in my code (line 24 is stmt.executeBatch();
In both of your SQLs, there is no space between the concatenation of the amount and the word WHERE -- it looks like this: checkingbalance-100WHERE id=.
Place a space before both WHERE words.
stmt.addBatch("UPDATE bank SET checkingbalance = checkingbalance-"
// +- Add space here
// v
+amount+" WHERE id="+id);
Change your withdrawfromchecking and Depositinsaving methods to this:
public static void withdrawfromchecking(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
statement.addBatch("UPDATE bank SET checkingBalance = checkingBalance - " +amount+ " WHERE id =" + id);
}
public static void Depositinsaving(Connection connection, Statement stmt, BigDecimal amount, long id) throws SQLException{
statement.addBatch("UPDATE bank SET savingBalance = savingBalance + " +amount+ " WHERE id =" + id);
}
The first step would be to put the update statement in a string and examine the value after concatenation.
Ideally you should be using parameterized prepared statements instead of dynamically concatenating the sql.
I created this code to allow me calculate the number of rows in my table. However, I'm not able to return the counted number with an error saying "cannot return a value from method whose result type is void." Could someone show me where' my error? Thanks alot!
public void num() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from testdb.emg");
int count = 0;
while (resultSet.next()) {
count++;
}
return count;
} catch (Exception e) {
}
Try below code
public int num() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
resultSet = statement.executeQuery("select count(*) from testdb.emg");
while (resultSet.next()) {
return resultSet.getInt(1);
}
} catch (Exception e) {
}
Below were error
public void num() throws Exception {
should be
public int num() throws Exception {
For counting total rows you should use query select count(*) from testdb.emg
Let me know incase of any problem.
Change
public void num() throws Exception {
to
public int num() throws Exception {
You are returning value from variable count which is of type int therefore the return type of the method should be int as well.
You should also make sure there is a return statement in every execution path through your code including the exception handler in the catch blocks (or you will get a "missing return statement" error message). However, it is best to avoid catch statements which catch all exceptions (like yours). Also, ignoring (i.e. not handling) exceptions in the catch block often leads to hard to diagnose problems and is a bad practice.
There are also other problems with the code: with the exception of count none of your variables have been declared.
Note that you may use the following SQL statement to obtain the number of rows directly:
select count(*) from testdb.emg
This avoids sending all of the data from table testdb.emg to your application and is much faster for big tables.
How to get count(*) mysql data table in java.
TRY IT:
public int getRowNumber(){
int numberRow = 0;
Connection mysqlConn = DriverManager.getConnection(HOST, USER_ID, PASSWORD);
try{
mysqlConn.getConnection();
String query = "select count(*) from dataTable";
PreparedStatement st = mysqlConn.preparedStatement(query);
ResultSet rs = st.executeQuery();
while(rs.next()){
numberRow = rs.getInt("count(*)");
}
}catch (Exception ex){
System.out.println(ex.getMessage());
}
return numberRow;
}
public void num() throws Exception {
should be
public int num() throws Exception {
I use Fahim Parker answer with a bit change
`
public int num() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery("<your query statement>");
resultSet.last(); //go to last row;
return resultSet.getRow(); //get row number which is equal to rows count
} catch (Exception e) {
}
`
This question already has answers here:
java.sql.SQLException: No database selected - why?
(4 answers)
Closed 3 years ago.
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"
//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
public class DataBase {
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
// 2.open a data source name by means of the jdbcodbcdriver.
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
Statement stmt = con.createStatement();
// Shut off autocommit
con.setAutoCommit(false);
System.out.println("1.Insert 2.Delete 3.Update 4.Select");
Scanner s = new Scanner(System.in);
int x;
x = s.nextInt();
String query; // SQL select string
ResultSet rs; // SQL query results
boolean more; // "more rows found" switch
String v1, v2; // Temporary storage results
Vector<Object> results = new Vector<Object>(10);
if (x == 1) {
try {
stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
} catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
}
if (x == 2) {
try {
stmt.executeUpdate("DELETE from employee where emp_id='102' ");
}catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
if (x == 3) {
try {
stmt
.executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
} catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
query = "SELECT * FROM employee ";
try {
rs = stmt.executeQuery(query);
// Check to see if any rows were read
more = rs.next();
if (!more) {
System.out.println("No rows found.");
return;
}
// Loop through the rows retrieved from the query
while (more) {
v1 = "ID: " + rs.getInt("emp_id");
v2 = "Name: " + rs.getString("emp_name");
System.out.println(v1);
System.out.println(v2);
System.out.println("");
results.addElement(v1 + "\n" + v2 + "\n");
more = rs.next();
}
rs.close();
} catch (SQLException e) {
System.out.println("" + results.size() + "results where found.");
}
finally{stmt.close();}
}
public static void main(String[] args) throws SQLException {
String str = "y";
do {
DataBase s = new DataBase();
s.LoadDriver();
DataBase.connect();
Scanner sc = new Scanner(System.in);
System.out.println("DO u Want to PROCEED TO QUERY : ");
str = sc.next();
} while (str !="n");
}
}
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.
then
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
Statement stmt = con.createStatement();
...
Just from looking at the exception.. I would guess that you are not specifying the database.
How can you do a select on a table without telling it which schema to select from ?
This is typically set in the connection string..
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool?
If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter.
But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still.
while (str !="n")
That's not how you compare strings in Java.
Found a bug listing at MySQL that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well.
Some things that stick out as odd to me (although no clue if they will have any impact on your error)
You only need to load the Driver Manager once
You aren't closing your connection, so either close it or refactor to use the same one.
Perhaps move these two lines to just before the do loop
DataBase s = new DataBase();
s.LoadDriver();