jsp mysql inserting error - java

this is y inserting syntax
String add="INSERT INTO time_table VALUES("+coursename+"','"+coursecode+"','"+days+"','"+year+"','"+dep+"','"+time+"','"+hall+"','"+lecturer+"','"+credithours+"')";
ERROR
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','5','2','2','8','1','9','PA','2')' at line 1
that is what am receiving as an error.

I think correct version of your query is this :
"INSERT INTO time_table VALUES('"+coursename+"','"+coursecode+"','"+days+"','"+year+"','"+dep+"','"+time+"','"+hall+"','"+lecturer+"','"+credithours+"')";
you forgot ' in beginning of +coursename+

Don't ever use this way, it can cause Syntax error, ot SQL Injection, you have to use PreparedStatement instead for example :
String add = "INSERT INTO time_table VALUES(?, ?, ?, ?, ?,?,?,?,?)";
try (PreparedStatement insert = connection.prepareStatement(add)) {
insert.setString(1, coursename);
insert.setString(2, coursecode);
insert.setString(3, days);
insert.setString(4, year);
insert.setString(5, dep);
insert.setString(6, time);
insert.setString(7, hall);
insert.setString(8, lecturer);
insert.setString(9, credithours);
insert.executeUpdate();
}
Note if your attributes are int or float or date or ... in your table, then you have to use the correct set, for example if the year is an in you can use insert.setInt(4, year); instead.
Your real problem is in your query you miss ' here :
INSERT INTO time_table VALUES('" + coursename + "'
//----------------------------^

Related

Java JDBC SQL rewriting one table to another [duplicate]

I would like to have a value from a row inserted into an other row here is my code:
static void addVipMonth(String name) throws SQLException
{
Connection conn = (Connection) DriverManager.getConnection(url, user, pass);
PreparedStatement queryStatement = (PreparedStatement) conn.prepareStatement("INSERT INTO vips(memberId, gotten, expires) " +
"VALUES (SELECT name FROM members WHERE id = ?, NOW(), DATEADD(month, 1, NOW()))"); //Put your query in the quotes
queryStatement.setString(1, name);
queryStatement.executeUpdate(); //Executes the query
queryStatement.close(); //Closes the query
conn.close(); //Closes the connection
}
This code is not valid. How do I correct it?
I get an error 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 – sanchixx
It was due to error in SELECT .. statement.
Modified statement is:
INSERT INTO vips( memberId, gotten, expires )
SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
FROM members WHERE id = ?
You don't require VALUES key word when inserting with a select.
You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval).
You can try your insert statement as corrected below:
INSERT INTO vips( memberId, gotten, expires )
SELECT name FROM members
WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
Refer to:
INSERT ... SELECT Syntax
DATE_ADD(date,INTERVAL expr unit)

Getting SQL error SQL State S1009

I'm trying to insert values into a table (inquiry) the first value is of type Date , and I'm getting an SQL error SQL State S1009. what is the proper way to convert the date , what am I doing wrong?
String sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
ps = con.prepareStatement(sqlStatement);
java.sql.Date sDate = new java.sql.Date(inquiry.getInquiryDate().getTime());
int parameterIndex = 1;
ps.setDate(parameterIndex, sDate);
ps.setString(parameterIndex++, inquiry.getInquiryNote());
ps.setInt(parameterIndex++, inquiry.getInquirer().getInquirerID());
ps.setInt(parameterIndex++, inquiry.getProgramID());
ps.setInt(parameterIndex++, inquiry.getClassProgramID());
ps.setInt(parameterIndex++, 1);
sqlStatement = "INSERT INTO inquiry (INQUIRY_DATE,INQUIRY_NOTE,INQUIRER_ID,PROGRAM_ID,CLASS_ID,CORPORATE_ID)\n"
+ "VALUES (?,?,?,?);";
The parameterized query doesn't have enough ?, you queried 6 columns with 2 ? missing, it should be VALUES (?,?,?,?,?,?); ? are used for holding the places for your setXXX() column values

Insert String in HSQLDB

I try to insert a String into a hsqldb an it gives me this error:
> java.sql.SQLSyntaxErrorException: user lacks privilege or object not
found: S
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
the column is set to VARCHAR(50) and the sqlstring is build like this:
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +"," + "\""+ emergency.typeD +"\"" + "," + "\""+
emergency.typeB +"\"" + ","+ emergency.floorID + ")";
this ist how i execute the query:
Statement st = null;
st = con.createStatement(); // statements
int i = st.executeUpdate(sql); // run the query
PS: I know i am open to a sqlInjection like this.
EDIT: values are
sql = "INSERT INTO Emergency Values(0,1,"S","IB",1)"
If i change the string to ;
String sql = "INSERT INTO Emergency Values(" + Counter.emergencyID + ","+
emergency.status +","+ emergency.typeD +","+ emergency.typeB +","+
emergency.floorID +")";
the same error occures
Use a PreparedStatement and you won't have problems:
String sql =
"INSERT INTO Emergency (emergency_id, status, type_d, type_b, floor_id) " +
" Values (?, ?, ?, ?, ?)";
Note that I explicitly listed the column names in the insert statement. Not doing that is considered bad coding style.
I had to guess those names as you didn't show us the definition of your table. You have to replace with the correct column names of your table.
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
The root cause of your problem was the incorrect usage of double quotes: ". String constants have to be put in single quotes in SQL. 'foobar' is a string value. Double quotes are used for identifiers "foobar" is e.g. a column name.
Unrelated, but: the use of Counter.emergencyID lets me think that your are generating (or trying to) unique IDs in your application. Don't do that. Use a sequence or identity column in the database. Do it correctly from the beginning. For a single user application this might not make a difference, but there is no way you can implement that correctly and scalable in an application that is used by multiple users at the same time, with concurrent transactions inserting into the same table.
i found the error in #a_horse_with_no_name 's code
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, Counter.emergencyID);
pstmt.setInt(2, emergency.status);
pstmt.setString(3, emergency.typeD);
pstmt.setInt(4, emergency.typeB);
pstmt.setInt(5, emergency.floorID);
int i = pstmt.executeUpdate(sql); // run the query
note the last line, it should be
int i = pstmt.executeUpdate(); // run the query
please refer to HSQLDB cryptic exception message: "feature not supported"
I know the question is old, but I ran into the same problem and found my a solution without using PreparedStatements.
INSERT INTO TypeA (id) VALUES ("Hello");
failed (user lacks privilege or object not found: Hello ), but
INSERT INTO TYPEA (id) VALUES ('Hello');
worked. So it seems like double quotes are not accepted (see also http://www.hsqldb.org/doc/1.8/guide/ch09.html#expression-section )

java sql syntax error

i'm writing this code to get the values from textfields and update a register in my database.. but it shows "Syntax error : Encountered "\" at line 1,column 196
and when i select another row from the jtable the column number in syntax error change..Can anyone tell me what's the wrong here and how can i fix it
here's the code :
String up = "UPDATE BENEFICTOR SET ID='"+T1.getText().toString()+"', FID='"+T2.getText().toString()+"', FULLNAME='"+T3.getText().toString()+"', GENDER='"+T4.getSelectedItem().toString()+"', IDNUM='"+T5.getText().toString()+"', STATUS='"+T6.getSelectedItem().toString()+"', ORIGINALAREA='"+T7.getText().toString()+"', RECENTAREA='"+T8.getText().toString()+"', EVAL='"+T9.getSelectedItem().toString()+"', PHONENYMBER1='"+T10.getText().toString()+"', PHONENUMBER2='"+T11.getText().toString()+"', SITUATION='"+T12.getText().toString()+"', VISIT='"+T13.getText().toString()+" WHERE ID="+T1.getText().toString();
Get rid of that code and use a PreparedStatement. The PreparedStatement will replace each "?" for you with the related parameter and use the proper delimiters:
To get you started:
String sql = "UPDATE BENEFICTOR SET ID = ?, FID = ?, .... WHERE ID = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, T1.getText() );
stmt.setString( 2, T2.getText() );
...
stmt.setString( ?, T1.getText() );
stmt.executeUpdate();
stmt.close();
assemble sql like this is not smart,you have just miss a ','
VISIT='"+T13.getText().toString()+" WHERE ID="+T1.getText().toString();
and the other careless behaviour is ...
"UPDATE BENEFICTOR SET ID='"+T1.getText().toString()+"',
" WHERE ID="+T1.getText().toString();
focus on the quotes that you added at first.

insert in select in MySQL with JDBC

I would like to have a value from a row inserted into an other row here is my code:
static void addVipMonth(String name) throws SQLException
{
Connection conn = (Connection) DriverManager.getConnection(url, user, pass);
PreparedStatement queryStatement = (PreparedStatement) conn.prepareStatement("INSERT INTO vips(memberId, gotten, expires) " +
"VALUES (SELECT name FROM members WHERE id = ?, NOW(), DATEADD(month, 1, NOW()))"); //Put your query in the quotes
queryStatement.setString(1, name);
queryStatement.executeUpdate(); //Executes the query
queryStatement.close(); //Closes the query
conn.close(); //Closes the connection
}
This code is not valid. How do I correct it?
I get an error 17:28:46 [SEVERE] com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MyS QL server version for the right syntax to use near ' NOW(), DATE_ADD( now(), INT ERVAL 1 MONTH )' at line 1 – sanchixx
It was due to error in SELECT .. statement.
Modified statement is:
INSERT INTO vips( memberId, gotten, expires )
SELECT name, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
FROM members WHERE id = ?
You don't require VALUES key word when inserting with a select.
You used a wrong DATEADD function syntax. Correct syntax is Date_add( date_expr_or_col, INTERVAL number unit_on_interval).
You can try your insert statement as corrected below:
INSERT INTO vips( memberId, gotten, expires )
SELECT name FROM members
WHERE id = ?, NOW(), DATE_ADD( now(), INTERVAL 1 MONTH )
Refer to:
INSERT ... SELECT Syntax
DATE_ADD(date,INTERVAL expr unit)

Categories