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

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");
}

Related

Java updating mysql row if id already exists

I have a simple form with 5 fields. (txtID, txtFirstName, txtLastName, txtCheque, txtSavings). All I want to do is inserting these fields into my database table "accounts". Before that step I want to check if the ID from my txtID field already exists in my database. If yes then I want to update the database row with the content from the fields. And if not I want to create a new row with the content. So far the check if the ID exists in my DB works but if click on my btn I get the following error message: I dont relly know what I'm doing wrong.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near '(LastName,
FirstName,Cheque,Savings) VALUES('Tester','Markus','450.00','50.00" at
line 1
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String id = txtID.getText();
String checkid ="SELECT * FROM accounts where ID=?";
pst=conn.prepareStatement(checkid);
pst.setString(1, id);
rs = pst.executeQuery();
boolean recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if(recordAdded){
// the statement for inserting goes here.
}else{
String sql ="UPDATE accounts SET " + "(LastName,FirstName,Cheque,Savings) VALUES" + "(?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.executeUpdate();
getAllAccounts();
JOptionPane.showMessageDialog(null, "Customer Updated");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
getAllAccounts();
}
catch(Exception e) {
}
}
}
do you let me to make some changes in your code?
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "UPDATE accounts SET LastName = ?, FirstName = ?, Cheque = ?, Savings = ? where id = ?";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.setString(5,txtID.getText());
int updatedRowCount = pst.executeUpdate();
// no record with id = txtID
if(updatedRowCount == 0) {
pst.close();
sql = "insert into accounts (ID,LastName,FirstName,Cheque,Savings) values (?,?,?,?,?,?) ";
pst = conn.prepareStatement(sql);
pst.setString(1,txtID.getText());
pst.setString(2,txtLastName.getText());
pst.setString(3,txtFirstName.getText());
pst.setString(4,txtCheque.getText());
pst.setString(5,txtSavings.getText());
pst.executeUpdate();
}
getAllAccounts();
JOptionPane.showMessageDialog(null, updatedRowCount > 0 ? "Customer Updated" : "Customer Inserted");
}
catch(Exception e){
getAllAccounts();
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
pst.close();
}
catch(Exception e) {
}
}
}

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 ( ...

how to insert value from jtable to mysql?

Im trying to insert data from jtable to database!! the first three columns(stafftimetableid,staffname,staffid) are inserted from the jtexfield(no errors found,successfully added) but when im trying to insert from jtable it promts a java.null pointerExcetion error !!
I have no errors in database connection !!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jComboBox1.getSelectedItem().equals("Staff Time Table"))
{
try
{
PreparedStatement pst =null;
Connection con = clerkpanell.DBConnection.connectDB();
String data=jTable2.getValueAt(0,1).toString();
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
pst=con.prepareStatement(sql);
pst.executeUpdate();
// JOptionPane.showMessageDialog(null,"Added");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
In this statement String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
Please store the ttid.getText(), staffname.getText(),staffid.getText()into separate variables. Something like this,
String ttid=ttid.getText();
String staffname = staffname.getText();
String staffid = staffid.getText();
and then the insert statement should be something like this
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.+"','"+staffname+"','"+staffid+"','"+data+"');";

Java : SQL syntax error for entering values in Table

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.

How to delete a record (string) JAVA and MYSQL

I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");

Categories

Resources