SQL Error or missing database syntax error - java

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.

Related

Why is an error arising in updating info into SQL Database from Java code?

I am writing the code for a sign-up page for a system. Once the button is clicked, the system will check if the user is above the age of 14. If true, the system should save all the inputted data into a SQL Database.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int age = Integer.parseInt(Age_Input.getText());
String firstname = FirstName_Input.getText();
String surname = Surname_Input.getText();
String email = Email_Input.getText();
String userid = UserID_InputSignUp.getText();
char[] pass = Password_InputSignUp.getPassword();
if (age<14) {
JOptionPane.showMessageDialog(null,"Sorry, You need to be at least 14 years to use this software... ");
new Login_Page().setVisible(true);
this.setVisible(false);
} else {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info", "root", "nerdswonka");
Statement stmt = connect.createStatement();
String query1 = "INSERT INTO user_info(user_id, password, firstname, lastname, emailid, age) VALUES('"+userid+"', "+Arrays.toString(pass)+", '"+firstname+"', '"+surname+"', '"+email+"', "+age+");";
stmt.executeUpdate(query1);
JOptionPane.showMessageDialog(null, "Account Creation succesful!");
stmt.close();
connect.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error in connecting to SQL Database");
}
new Login_Page().setVisible(true);
this.setVisible(false);
}
}
The code isn't updating anything into the database and is simply showing JOptionPane after an exception (error ) comes. What edits can be done to the code so that values get stored into SQL?
The immediate cause of the failure is probably that your INSERT statement contains the following string which is not being single quoted:
Arrays.toString(pass)
However, you should completely abandon your current approach and instead use a prepared statement:
String sql = "INSERT INTO user_info (user_id, password, firstname, lastname, emailid, age) " +
"VALUES (?, ?, ?, ?, ?, ?)";
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info", "root", "nerdswonka");
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, userid);
ps.setString(2, Arrays.toString(pass));
ps.setString(3, firstname);
ps.setString(4, surname);
ps.setString(5, email);
ps.setInt(6, age);
int row = ps.executeUpdate();
System.out.println(row); // rows inserted (should be 1)
}
catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
Prepared statements do many things, one of which is handling the messy details about how to properly escape your literal data in a SQL query. In this case, they free you from having to worry about placing single quotes around your interpolated Java strings. Statements also prevent bad things like SQL injection from happening.
You are not printing your exception in catch block. You can use e.printStackTrace(); to print exception first.

Number of columns for result set error in SQL database for Java app

I'm having an issue with adding data to a sql database through Java on Netbeans.
String bladeSerial;
String bladeType;
LocalTime startTime1;
private void startButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println ("Successful Connection");
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
I get the error The column position '1' is out of range. The number of columns for this ResultSet is '0'.
In the database, Serial is VARCHAR(5), Bladetype is VARCHAR(80)and StartT1 is VARCHAR(12)
The startTime1 variable is saved in the format HH:mm:ss.SSS.
I appreciate any help on this error
You need to give placeholder in your query. Change your code as given here...
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
You don't need to give column names in query when you are using Prepared statement. Do the following changes:
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
Hope it helps!!
Here you are forming query like simple statement and used it in prepared statement which is not possible, so change your query with place holder like below.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
If you want to directly use variables names like bladeSerial, then you should use these String variables as if you're adding multiple Strings.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ("+bladeSerial+", "+itemText+", "+(String.valueOf(startTime1))+")";
But this is strictly not recommended as it would introduce serious security issues.
The recommended way is to use PreparedStatement. The query you've written is correct, it's just that you have to use placeholders instead of variable names.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}

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

quotation marks in string parameter insert statement

Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.

How to avoid MySQLSyntaxErrorException

I am using Java to insert some data into mysql . But having apostrophe(punctuation mark) into data (near's weekly tracker suggests that job growth) it gives me MySQLSyntaxErrorException.Please give me proper solution to handle that
Code I have isa
void insert(String a1,String a2, String a3) {
String nt = a2;
String pt = a3;
String tb = a1;
query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')";
try {
stmt.executeUpdate(query);
System.out.println("inserted"); //con.close();
} catch (SQLException ex) {
// Logger.getLogger(conec.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
Use query parameters, not string concatenation. This will allow the database driver to format the values you send to the database server, rather than re-inventing this wheel yourself.
String sql = "insert into ... values (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, nt);
stmt.setString(2, pt);
stmt.executeUpdate();
query = "insert into "+tb+"(head,des) values('"+nt+"','"+pt+"')";
should be
query = "insert into "+tb+" (head, des) values ('"+nt+"','"+pt+"')";
Please do these changes and let me know if there are still problems....

Categories

Resources