i'm a new programmer, I was given a task to create a class Subject.java, in which it'll ask the students how many subjects they're taking and then store the subjects information into the database, but the problem with my current code is that only one row is updated in the database. My code is as the following, please help me.
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i=0;
for (i=0; i<sub; i++)
{
System.out.print("\nCode: ");
this.setCode(in.next());
System.out.print("\nName: ");
this.setName(in.next());
System.out.print("\nCredit: ");
this.setCredit(in.nextInt());
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
try (Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);)
{
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt (3, this.getCredit());
pstmt.addBatch();
if (pstmt.executeUpdate() == 1)
{
System.out.println("\nNew subject has been created succesfully!");
}
else
{
System.out.println("\nError");
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
As Nexevis said , you need to put your Connection code outside your for-loop like below :
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i = 0;
try {
Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);
for (i = 0; i < sub; i++) {
System.out.print("\nCode: ");
this.setCode( in.next());
System.out.print("\nName: ");
this.setName( in.next());
System.out.print("\nCredit: ");
this.setCredit( in.nextInt());
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt(3, this.getCredit());
pstmt.addBatch();
}
try {
// execute it to insert the data
pstmt.executeBatch();
} catch (SQLException e) {
System.out.println("Error message: " + e.getMessage());
return; // Exit if there was an error
}
pstmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
Related
I can only get results from a SQL query execution when I use select columnname from tablename, but not when I use select * from tablename
public static void connectAndExecute(String host, String uName, String uPass, String sqlQuery) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
} catch (SQLException e) {
e.printStackTrace();
}
try {
Connection con=DriverManager.getConnection(host, uName, uPass);
String[] conData = null;
Statement stmt = null;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
/*this is the place of my problem*/
}
catch (SQLException e) {
e.printStackTrace();
}
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Use ResultSet.class methods to get the desired result. You can give the column names or column index.
getInt(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as an int in the Java programming language.
getString(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Here is how you can implement it:
while(rs.next()){
//Retrieve by column index
int id = rs.getInt(1); //assume id is at 1st index
int age = rs.getInt(4); //assume age is at 4th index
String first = rs.getString(2); // assume first name is at 2nd index
String last = rs.getString(3); // assume last name is at 3rd index
//Display values
System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last);
System.out.println(" End of one row");
}
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
Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}
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;
}
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);
}
}