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
Related
I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.
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();
I have this piece of code where I prompt the user to enter the depID to edit a department and then through the IF statement I have done it displays either saved or department doesn't exists. Now my problem is that it's going directly to the else statement. When I used debugging I noticed that the RS (ResultSet) is only comaring the users input to the first row of the table which is AOL.
try{
String value1 = txt_depID.getText();
String value2 = txt_depName.getText();
String sql = "Update tblDepartment set depID = '"+value1+"' , depName = '"+value2+"' where depID = '"+value1+"'";
String sql1 = "Select depID, depName from tblDepartment";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
rs = ps.executeQuery();
ps = conn.prepareStatement(sql);
ps.execute();
if(rs.next()){
String depi = rs.getString("depID"); //Issue: only reading first row
if(depi.equals(value1)){
JOptionPane.showMessageDialog(null, "Entry Saved");
}
else{
JOptionPane.showMessageDialog(null, "Department doesn't exist");
}
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
You can do this in one cycle. You should be using executeUpdate.
String sql = "Delete from tblEmployee where staffNo=?";
String sql1 = "Select * from tblEmployee";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
int result = ps.executeUpdate();
if (result > 0) {
// success
}
Here's what executeUpdate results:
Returns: either (1) the row count for SQL Data Manipulation Language
(DML) statements or (2) 0 for SQL statements that return nothing
I am just trying to insert a new row in a table from a java application to an SQL database. I have used the same code before and it worked but for some reasons this doesn't. I have checked my query by inserting it directly in phpmyadmin and it works. Here is my code:
where I actually try to sent the query:
static Connection conn = MySQLAccess.connectDB();
static PreparedStatement pst = null;
static ResultSet rs = null;
public static String submit(String usrn, String psw){
String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
try {
pst = conn.prepareStatement(sql);
System.out.println(sql);
rs=pst.executeQuery();
if (rs.next()){
return "ok";
} else {
return "fail";
}
} catch (Exception e){
return "fail_connection";
}
}
MySQLAccess.java (which I am sure works because I use is at other points in the code):
public class MySQLAccess {
Connection conn=null;
public static Connection connectDB (){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/g52gui","root","");
return conn;
}catch(Exception e){
return null;
}
}
}
I have just changed my code (suggestion of Luiggi Mendoza) but no result:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}
Three issues:
Use PreparedStatement#executeUpdate rather than PreparedStatement#executeQuery.
Keep the variables in the narrowest possible scope. Don't set them as static variables in your class.
Don't concatenate the parameters into the query string. Instead, use PreparedStatement#setXyz method to set the proper parameter.
Gluing all of these together produces the following code:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}
From your new code, the problem is here:
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
^ ^ ^ ^
You're wrapping the parameter character ? with quotes '. Remove such quotes, as shown in my code:
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
//No quotes around ?
You should use executeUpdate and not executeQuery;
I am developing an application with java on netbeans/windows 7. I was trying to insert data to database with PreparedStatement using SQL. So this is my code;
private void addInfoActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn;
PreparedStatement pst;
String url = "jdbc:derby://localhost:1527/records";
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
String name, surname, number;
try {
conn = DriverManager.getConnection(url, "system", "app");
System.out.println("connected to db");
pst = conn.prepareStatement(SQL_INSERT);
name = nameField.getText();
surname = surnameField.getText();
number = numberField.getText();
System.out.println("got data from textfields");
pst.setString(1, name);
pst.setString(2, surname);
pst.setString(3, number);
System.out.println("variables set");
pst.executeUpdate();
System.out.println("sql command executed");
pst.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(addition.class.getName()).log(Level.SEVERE, null, ex);
}
}
But I got an error like this;
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at
line 1, column 27.
Name of my table is records and it has three coloumns named; name, surname and number. As I can understand from the println lines, there is a problem with that line;
pst = conn.prepareStatement(SQL_INSERT);
or maybe I created SQL_INSERT string and SQL code wrong. I couldn't figure out what is the problem exactly.
You're missing a space in
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
When you do the concatenation, it produces "INSERT INTO recordsVALUES(?,?,?)"
Change it to
String SQL_INSERT = "INSERT INTO records"+
" VALUES(?,?,?)";