Java : SQL syntax error for entering values in Table - java

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.

Related

SQLite database refuses to update and I'm not sure why

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
}

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ')'

Iam getting a error in String qquery when i run the code Incorrect syntax near ')'. my sql qquery is running well in sqlserver he minus the products quantity .Any idea ? ty
error log
at mylogin.Basket.makesales(Basket.java:160)
at mylogin.Basket.ReceiptActionPerformed(Basket.java:455)
at mylogin.Basket.access$100(Basket.java:23)
Here is my code
public void executeSQLQuery (String query,String message) {
Connection con =getConnection();
Statement st;
try{
st =con.createStatement();
if((st.executeUpdate(query))==1)
{
con.commit();
DefaultTableModel model=(DefaultTableModel)jTable_ProSales.getModel();
model.setRowCount(0);
show_Basket_in_Jtable();
JOptionPane.showMessageDialog(null,"Data "+message+" Succefully");
}else{
JOptionPane.showMessageDialog(null,"Data Not "+message+ "Error");
}
}catch (Exception ex){
ex.printStackTrace();
}
}
action button
private void ReceiptActionPerformed(java.awt.event.ActionEvent evt) {
String query= "INSERT INTO Sales (Pro_Id ,Pro_Name,Sales_Quantity,Pro_Price ) SELECT Pro_Id,Pro_Name,Sales_Quantity ,Pro_Price FROM Receipt";
executeSQLQuery(query,"Inserted");
String qquery= " UPDATE Products SET Pro_Quantity= Products.Pro_Quantity - Receipt.Sales_Quantity FROM Products INNER JOIN Receipt ON Products.Pro_Id = Receipt.Pro_Id)" ;
executeSQLQuery(qquery,"updated");
}
private void ReceiptActionPerformed(java.awt.event.ActionEvent evt) {
String query= "INSERT INTO Sales (Pro_Id ,Pro_Name,Sales_Quantity,Pro_Price ) SELECT Pro_Id,Pro_Name,Sales_Quantity ,Pro_Price FROM Receipt";
executeSQLQuery(query,"Inserted");
String qquery= " UPDATE Products SET Pro_Quantity= Products.Pro_Quantity - Receipt.Sales_Quantity FROM Products INNER JOIN Receipt ON Products.Pro_Id = Receipt.Pro_Id" ;
executeSQLQuery(qquery,"updated");
}

this net beans code gives " syntax error in insert into statement".. kindly tell me the right way

The following code used to run with another database with 4 variables. however, I am getting error this time..
private void jButton2ActionPerformed(java.awt.event.ActionEventevt){
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con=DriverManager.getConnection("jdbc:odbc:Database2");
try (Statement stmt = con.createStatement()) {
String a=jTextField2.getText();
String b=jTextField3.getText();
String c=jTextField4.getText();
String d=jTextField5.getText();
String e=jTextField12.getText();
String f= jTextField13.getText();
String g = jTextField14.getText();
int query;
query =stmt.executeUpdate("INSERT INTO ProductDatabase" + " (Id, Product, Price, Discount, Stock, Sold, Left)" + "VALUES('"+(a)+"','"+(b)+"','"+(c)+"','"+(d)+"','"+(e)+"','"+(f)+"','"+(g)+"')"); //insert query
System.out.println("inserted");
}
con.close();
}
catch(ClassNotFoundException | SQLException e)
{
System.err.println("Exception: "+e.getMessage());
} // TODO add your // TODO add you
}
LEFT is reserved word in Access SQL, so you need to enclose that column name in square brackets:
INSERT ... Discount, Stock, Sold, [Left]) VALUES ( ...

PostgreSQL JDBC Driver rounds crops double value

I'm using PostgreSql 9.3 together with the postgresql-9.3-1101 JDBC Driver.
And there is a really strange behavior with the PreparedStatements.
Here is the example:
First I create a test table:
CREATE TABLE double_test
(
id numeric(18) NOT NULL
);
After that that i run following code:
DecimalFormat df = new DecimalFormat("0");
try {
conn = BeanUtils.getBean("dataSource", DataSource.class).getConnection();
conn.setAutoCommit(false);
conn.createStatement().execute("DELETE from double_test ");
conn.commit();
PreparedStatement stmt = conn.prepareStatement("INSERT INTO double_test (id )VALUES (?)");
double input = 1234567890123456d;
System.out.println("Input:" + df.format(input));
stmt.setDouble(1, input);
stmt.execute();
conn.commit();
ResultSet rs = conn.createStatement().executeQuery("SELECT id FROM double_test ");
rs.next();
System.out.println("Output:" + df.format(rs.getDouble(1)));
rs.close();
} catch (SQLException e1) {
throw new RuntimeException(e1);
} finally {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The output of the code will be:
Input: 1234567890123456
Output:1234567890123460
Which gets me very confused, after the 15. digit the Postgres JDBC Driver starts to round. The inserted data gets corrupted, without any further notice!
Did I miss anything here? Has my code any errors?
Or is this a bug in the Driver? If so, I really wonder that no one noticed this yet.
Maybe working with BigDecimal will prevent the data from corrupting, but this is just a workaround.
There is a two problem.
First from Double class:
System.out.println(0.1 + 0.2); //output 0.30000000000000004
So usually don't use Double (also Float).
Second from jdbc driver , it is triying to save database with toString method which class related with org.postgresql.jdbc.PgPreparedStatement.
Check this:
System.out.println(new BigDecimal("0.00000072")); // print 7.2E-7
It is equal but when Jdbc driver save with this, some precisions corrupt, so I replace
public void setBigDecimal(#Positive int parameterIndex, #Nullable BigDecimal x)
throws SQLException {
setNumber(parameterIndex, x); // It is using toString method
}
with this:
public void setBigDecimal(#Positive int parameterIndex, #Nullable BigDecimal x)
throws SQLException {
checkClosed();
if (x == null) {
setNull(parameterIndex, Types.DECIMAL);
} else {
bindLiteral(parameterIndex, x.toPlainString(), Oid.NUMERIC); //now using toPlainString
}
}
If you really want to use Double or Float you can fix like this changes.

java mysql count number of rows

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) {
}
`

Categories

Resources