Insert query not executing - java

I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch

Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();

Related

How do I add the auto increment values with java?

I created a table in Mysql using
Create table
(
id int auto_increment,
us varchar(100),
ps varchar(1000)
);
And used java for adding values thru my GUI application:
I used the following method to add values into my database:
public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String hashpass=passhash(p);//throws declaration for this statement
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (id,us,ps)"
+ " values (?,?, ?)";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
int id=0;
while(rs.next())
{
id= rs.getInt(1);
}
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, id++); //I don't want this method because id is auto increment
preparedStmt.setString(2,u);
preparedStmt.setString(3,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){ System.out.println(e);}
}
Everything works fine
But the id is the auto_increment and I don't need to add value to id while adding other column values.
I can't add like that while adding thru java like only adding us, ps columns and the id will be automatically incremented.
Are there any methods to add data without passing the parameters?
Remove the column id from the sql statement:
String query = "insert into login (us, ps) values (?, ?)";
and don't set any value for it in the prepared statement, so remove this line:
preparedStmt.setInt(1, id++);
The column id is auto_inrement so its value will be set by MySql.
Of course change the indices of the other lines to 1 and 2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
You might insert data without ID as it will be auto-generated from SQL
public static void Mysql(String u,String p) throws NoSuchAlgorithmException, InvalidKeySpecException {
String hashpass=passhash(p);
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (us,ps) values (?, ?)"; // CHECK HERE
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){
System.out.println(e);}
}
}

Adding values to database table only once

I have to create a cart application in Spring MVC.
I have this cartentries table in database, where I store book_id,id_cartEntry and other fields. Also I have an user table, where I store id_user. I have similar entries in my cartentries, and when I click the checkout button, those entries have to be loaded into a cart table.
The problem is that I don't know how to store the id_user field into a variable, so that I do not have to have this line of code:
while (resultSet2.next())
This is making my code execute only once, so that only one entry from cartentries is loaded into the cart table. This is because the resultSet2 doesn't find any more new users in the table, because I am logged into a single user. How can I make all data from cartentries go into cart table?
This is the function:
#RequestMapping("/checkout")
public void checkout(#RequestParam String username) {
System.out.println("this is checkout from book controller");
System.out.println("username is " + username);
Connection connection = ConnectToDatabase.createConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("select * from cartentries");
ResultSet resultSet = preparedStatement.executeQuery();
PreparedStatement preparedStatement2 = connection.prepareStatement("select id_user from user where username='" + username + "'");
ResultSet resultSet2 = preparedStatement2.executeQuery();
while (resultSet.next()) {
while (resultSet2.next()) {
PreparedStatement preparedStatement1 = connection.prepareStatement("INSERT INTO cart(id_user,id_cartEntry,totalPrice)VALUES(?,?,?)");
preparedStatement1.setInt(1,resultSet2.getInt("id_user"));
preparedStatement1.setInt(2, resultSet.getInt("id_cartEntry"));
preparedStatement1.setInt(3, resultSet.getInt("totalPrice"));
preparedStatement1.executeUpdate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I've change your code to "store" the userid if it was found.
try {
PreparedStatement preparedStatement = connection.prepareStatement("select * from cartentries");
ResultSet resultSet = preparedStatement.executeQuery();
PreparedStatement preparedStatement2 = connection.prepareStatement("select id_user from user where username=?");
preparedStatement2.setString(1, username);
ResultSet resultSet2 = preparedStatement2.executeQuery();
PreparedStatement preparedStatement1 = connection.prepareStatement("INSERT INTO cart(id_user,id_cartEntry,totalPrice)VALUES(?,?,?)");
Integer userId;
if (resultSet2.next()) {
// guess it found at least one user
userId = resultSet2.getInt("id_user");
}
if (userId != null) {
while (resultSet.next()) {
preparedStatement1.setInt(1, userId);
preparedStatement1.setInt(2, resultSet.getInt("id_cartEntry"));
preparedStatement1.setInt(3, resultSet.getInt("totalPrice"));
preparedStatement1.executeUpdate();
}
}
} catch (Exception e) {
e.printStackTrace();
}
I've also change your userid query to use setString instead of concatenation. See SQLInjection
Maybe you can refactor those statements into separated methods for better code reading.
PS. Don't forget to add a finally clause and close the connection (or the try-with-resources) to prevent having a resource leaking on database server.

column not allowed here oracle with getText

I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again

How to use java variable to insert values to mysql table?

Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

What am I doing wrong with this preparedStatement?

private Connection conn = DriverManager.getConnection(URL, info);
try {
String sql = "INSERT INTO \"STUD1582251\".\"ACCOUNTS\" VALUES USERNAME=?, PASSWORD=?, PORTFOLIONAME=?";
PreparedStatement stm = conn.prepareStatement(sql);
stm.setString(1, user.getUsername());
stm.setString(2, user.getPassword());
stm.setString(3, user.getPortfolioName());
System.out.println(sql);
stm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
Exception
SELECT username FROM "STUD1582251"."ACCOUNTS" WHERE username=? INSERT
INTO "STUD1582251"."ACCOUNTS" VALUES USERNAME=?, PASSWORD=?,
PORTFOLIONAME=? java.sql.SQLSyntaxErrorException: ORA-00933: SQL
command not properly ended
INSERT SQL statement must be:
String sql = "INSERT INTO \"STUD1582251\".\"ACCOUNTS\" (USERNAME,PASSWORD,PORTFOLIONAME) VALUES (?,?,?)";
PS: Use " (double quotes) around identifier if it is a reserved word.

Categories

Resources