JAVA SQL command not properly ended - java

I have this code:
buy.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent actionEvent)
{
int r;
r = table.getSelectedRow();
String num = (String) table.getValueAt(r, 0);//numele jucariei
//String cop = (String) table.getValueAt(r, 3);//nr de bucati
try
{
pq = stmt.executeQuery("SELECT *" + "FROM buyid_view");
xv = stmt.executeQuery("SELECT toyid, copies " + "FROM alldatas_view" + "WHERE toyname ='"+num+"'");
int buyid = pq.getInt("buyid");
int toyid = xv.getInt("toyid");
int copies = xv.getInt("copies");
copies = copies-1;
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
cstmt.setInt("buyid", buyid);
cstmt.setInt("toyid", toyid);
ResultSet rs = cstmt.executeQuery();
JOptionPane.showMessageDialog(null, "You brought a toy.");
for(int i = 0; i < table.getRowCount(); i++)
for(int j = 0; j < table.getColumnCount(); j++)
table.setValueAt("", i, j);
try
{
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
}
int i = 0;
try
{
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try {
if(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
while(rs.next())
{
table.setValueAt(rs.getString(1), i, 0);
table.setValueAt(rs.getString(2), i, 1);
table.setValueAt(rs.getString(3), i, 2);
i++;
}
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
catch (SQLException e)
{
if(e.getMessage().contains("You have to pay!"))
warning(frame, "You didn't pay all your products");
else
warning(frame, e.getMessage());
}
}
});
When I compile my program I don't have any error but when I run it and I click on the buy button it gives me an error saying "ORA-00933: SQL command not properly ended".

When building SQL statements from strings you must ensure there are spaces where spaces are needed.
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
The statement you are sending is
SELECT *FROM availablebooks_view
which is invalid syntax. You have this problem in several places in your code.
However, you have a larger issue which results from building your SQL statements piecemeal. This leaves you open to SQL Injection and you should rewrite your code to use prepared statements and parameters instead.

There are multiple errors in your code
First one is
rs = stmt.executeQuery("SELECT *"+
"FROM availablebooks_view");
There is no space between * and FROM, this will actually creates a syntax error
Second one is
rs = stmt.executeQuery("UPDATE toys set copies "+ copies +"WHERE toyid= '"+toyid+"'");
There is no = after set copies, this will also create error.
Third one is
CallableStatement cstmt = con.prepareCall("INSERT INTO buy (buyid, toyid)" + "VALUES (?,?)");
Give space before VALUES

Related

how to sort a table from database

I want to be able to sort a table from the database, according to either the quatity or the name, but how do i decided what happens in what case?
Below is the code for the table.
public void tableupdate(JTable jTable1, String fill) {
try {
try {
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:file:D:/Inventory.db", "sa", "");
Statement stat = con.createStatement();
fill = "SELECT * FROM BOOKDESC ";
ResultSet rs = stat.executeQuery(fill);
while (jTable1.getRowCount() > 0) {
((DefaultTableModel) jTable1.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++) {
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) jTable1.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
con.close();
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, e);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
}
MySQL is offering a method for sorting data in your SELECT statement, it's called ORDER BY.
Usage is found here.
This way, your code doesn't have to do the work, as your ResultSet already gets sorted data.

APOSTROPHE issue with java and SQL

I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html

sqlite query using java

I'm working on shifts manager program which calculates monthly salary and etc.
the program based on SQLite database which keeps getting updated by the user input.
my question is , how can i use the SQLite function in java to retrieve information, lets say monthly salary in one command (i know i can use " select sum(tips) between date1 and date2",but how can i get the function result inside a variable?)
so far i've created a function which gets two dates and retrieves all the shifts salary between these dates and summarise them with ResultSet.
here's my code:
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select tips from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum += rs.getInt("tips");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}
I edited your code.
Note that in case you select the sum of the tips, the column name changes. You also get only one row with one column as your result, so you should not need the while loop anymore.
The sum of the tips is now saved in the variable sum
public static String tipsMade(String date1, String date2){
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ans= null;
int sum = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Gil\\test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery("select sum(tips) from shifts where fulldate between "+"'"+date1+"'"+"and " +"'"+date2+"'"+ ";");
while(rs.next()){
sum = rs.getInt("sum(tips)");
}
ans = Integer.toString(sum);
//
//close connections and etc
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
return ans;
}

java.sql.SQLException: [SQLITE_BUSY] The database file is locked

I am working in Eclipse with SQLite database, but I am facing the SQLITE_BUSY error. I've been reading for this problem for 2 days, and I have tried different things, such as closing PreparedStatement-s and Resultset-s every time or closing the connection. Even when i close a connection and open a new one, I get this error. Below is the code where i get the error. In this class there are several queries. The first ones being executed work fine, but when it comes to the last ones ( i mean the last being executed), the application crashes. I don't get it why this happens. I have seen almost all the posts for this problem, but still i couldn't fix it. Can anyone please help me? I really need to make it work. Thank you in advance!
My code:
//WHEN THIS METHOD IS CALLED I GET THE EXCEPTION
private void update(int a){
int index2=a;
try{String queryUpdate="Update Open_Orders set Quantity='"+mapTableProductQuantity.get(index2)+"' where Order_ID='"+orderID +"' and Table_ID='"+id_tavoline+"' and Product_ID='"+mapTableProductID.get(index2)+"'" ;
PreparedStatement pstUpdate = connection.prepareStatement(queryUpdate);
JOptionPane.showMessageDialog(null, "pst u be");
pstUpdate.execute();
JOptionPane.showMessageDialog(null, "u ekzekutua");
pstUpdate.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void updateDatabase()
{ mapName_ID= new HashMap <String, Integer>();
try{String query="Select Product_Name, Product_ID from Products";
PreparedStatement pst= connection.prepareStatement(query);
ResultSet rsp= pst.executeQuery();
//int no=0;
while(rsp.next()){
mapName_ID.put(rsp.getString("Product_Name"), rsp.getInt("Product_ID"));
}
pst.close();
rsp.close();
}catch(Exception e){
}
if(busy==0)
{
try{String query="insert into Order_Table (Table_ID) values (?)";
//System.out.println("busy eshte "+busy);
PreparedStatement pstInsert = connection.prepareStatement(query);
pstInsert.setInt(1, id_tavoline);
pstInsert.execute();
pstInsert.close();}
catch(Exception e1){
JOptionPane.showMessageDialog(null, "e1 = " +e1);
}
setOrderID();
int totalRows=table.getRowCount();
for(int row=0; row<totalRows;row++)
{
try{
String prName=table.getModel().getValueAt(row, 0).toString();
int quantity = Integer.parseInt(table.getModel().getValueAt(row, 1).toString());
String queryInsert="Insert into Open_Orders (Order_ID, Table_ID, Product_ID, Quantity) values (?,?,?,?)";
PreparedStatement pstInsert1 = connection.prepareStatement(queryInsert);
pstInsert1.setInt(1, orderID);
pstInsert1.setInt(2, id_tavoline);
pstInsert1.setInt(3, mapName_ID.get(prName));
pstInsert1.setInt(3, quantity);
pstInsert1.execute();
pstInsert1.close();
//,id_tavoline, mapName_ID.get(""));
}catch(Exception e ){
JOptionPane.showMessageDialog(null, e);
}
}
}
else {
mapTableProductID= new HashMap<Integer,Integer>();
mapTableProductQuantity=new HashMap<Integer,Integer>();
mapDBProductID = new HashMap<Integer,Integer>();
mapDBProductQuantity = new HashMap<Integer,Integer>();
setOrderID();
int totalRows=table.getRowCount();
int i=0;
for(int row=0; row<totalRows;row++)
{
String name=table.getModel().getValueAt(row, 0).toString();
System.out.println("name= " +name);
mapTableProductID.put(row, mapName_ID.get(name));
System.out.println(" mapName_ID.get(name)= " + mapName_ID.get(name));
System.out.println("mapTableProductID.get(row) = " +mapTableProductID.get(row));
mapTableProductQuantity.put(row, Integer.parseInt(table.getModel().getValueAt(row, 1).toString()));
}
try{connection= sqliteConnection.dbConnector();
String querySelect= "select Product_ID, Quantity from Open_Orders where Order_ID='"+orderID+"' and Table_ID='"+id_tavoline+"'";
PreparedStatement pstSelect = connection.prepareStatement(querySelect);
ResultSet rs=pstSelect.executeQuery();
while(rs.next()){
mapDBProductID.put(i, rs.getInt("Product_ID"));
mapDBProductQuantity.put(i, rs.getInt("Quantity"));
i++;
}
pstSelect.close();
rs.close();
connection.close();
}catch(Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
System.out.println("ne db ka i = " +i);
System.out.println("ne tabele ka = " +totalRows);
if(i>=totalRows){
System.out.println("Reshti 167");
int index1=0;
while(index1<i){
int index2=0;
//boolean found=false;
System.out.println("mapDBProductID.get(index1) = " +mapDBProductID.get(index1));
System.out.println("mapTableProductID.get(index2) = " +mapTableProductID.get(index2));
while((index2<totalRows)){
if(mapDBProductID.get(index1)!=mapTableProductID.get(index2)){
index2++;
}
else{//found=true;
System.out.println("Reshti 177");
if(mapDBProductQuantity.get(index1)!=mapTableProductQuantity.get(index2)){
System.out.println("Reshti 180");
System.out.println(orderID);
connection=sqliteConnection.dbConnector();
update(index2);
}else{
}
index1++;
break;
}
}
if(index2>=totalRows){
try{
String queryDelete="Delete from Open_Orders where Order_ID='"+orderID +"' and Table_ID='"+id_tavoline+"' and Product_ID='"+mapDBProductID.get(index1)+"'" ;
PreparedStatement pstDelete = connection.prepareStatement(queryDelete);
pstDelete.execute();
pstDelete.close();
}catch(Exception e4){
JOptionPane.showMessageDialog(null, "e4 = " +e4);
}
index1++;
}
}
}
if(i<totalRows){
int index1=0;
while(index1<totalRows){
int index2=0;
boolean found=false;
while((index2<i)&&(!found)){
if(mapTableProductID.get(index1)!=mapDBProductID.get(index2)){
index2++;
}else{found=true;
if(mapTableProductQuantity.get(index1)!=mapDBProductQuantity.get(index2)){
try{
String queryUpdate= "Update Open_Orders set Quantity='"+mapTableProductQuantity.get(index1)+"' where Order_ID='"+orderID +"' and Table_ID='"+id_tavoline+"' and Product_ID='"+mapTableProductID.get(index1)+"'" ;
PreparedStatement pstUpdate = connection.prepareStatement(queryUpdate);
pstUpdate.execute();
pstUpdate.close();
}catch(Exception e5){
JOptionPane.showMessageDialog(null, "e5 = " +e5);
}
}
break;
}
index2++;
}
if(index2>=i){
try {
String queryInsert="Insert into Open_Orders (Order_ID, Table_ID, Product_ID, Quantity) values (?,?,?,?)" ;
PreparedStatement pstInsert= connection.prepareStatement(queryInsert);
pstInsert.setInt(1, orderID);
pstInsert.setInt(2, id_tavoline);
pstInsert.setInt(3, mapTableProductID.get(index1));
pstInsert.setInt(1,mapTableProductQuantity.get(index1));
pstInsert.execute();
pstInsert.close();
}catch(Exception e10){
JOptionPane.showMessageDialog(null, "e10 = " +e10);
}
}
index1++;
}
}
}
}
private void setOrderID(){
try{
String query="select Order_ID from Order_Table where Table_ID='" + id_tavoline+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs=pst.executeQuery();
rs.next();
orderID=rs.getInt("Order_ID");
pst.close();
rs.close();
connection.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "setOrderID = "+e);
}
}

MySQL command SELECT values in column - JDBC

I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}

Categories