SQL Syntax Error in Java - java

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(?,?,?)";

Related

SQL Error or missing database syntax error

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.

JDBC INSERT not working

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;

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

Java sql delete row

Hello I am trying to delete a row from my database. I am getting no errors but it is doing nothing, any help or advice would be great!
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
I guess name is a varchar type in DB so do like this
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = '" + name + "';");
enclose name within single quotes '
Also this is not the way you are using is not the proper way of using Preparedstatement
Us the following way:
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
// your full code after Proper PreparedStatement
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = ?");
st.setString(1,name);
st.executeUpdate();
} catch(Exception e) {
System.out.println(e);
}
}
You should never create a SQL statement in Java with String concatenation, it will be vulnerable to sql injection. Please do it this way.
String selectSQL = "DELETE FROM Table WHERE name = ?";
connection.prepareStatement(selectSQL);
preparedStatement.setString(1, name);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "MANASH_APPN","MANASH");
PreparedStatement ps = con.prepareStatement("delete from EMP21 where empid = ?");
ps.setInt(1,90);
ps.executeUpdate();
con.commit();
System.out.println("Records Delete Successfully....");
con.close();
try this bro. use Statement
Statement stmt = connection.createStatement();
String SQL = "DELETE FROM Table WHERE name = '"+name+"'";
stmt.executeUpdate(SQL);
Every open connection must be closed, or it won't get implemented and no errors will be displayed. First learned lesson.
public static void DeleteRow(String name) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement st = connection.prepareStatement("DELETE FROM Table WHERE name = " + name + ";");
st.executeUpdate();
connection.close();
} catch(Exception e) {
System.out.println(e);
}
}
Hope this helps
this will work
String del="DELETE FROM table WHERE name =('" + name + "')";
:)

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