java mysql input NULL - java

I am using MySQL Server 5.6, Tomcat 8.0. I can create an SQL input statement that is successful in putting hard coded values into my table but if I try to use a variable instead, it appears as NULL in the table. I have println statements immediately before the SQL statement that show the right value in the variable. My syntax looks right and, as I said, it works for hard coded values.
Please excuse the code formatting. This is supposed to be a quick (HA!) and dirty proof of concept.
Code snippet:
// method to update spice table with input data
public void update()
{
System.out.println("Starting Update");
java.sql.Date useDate = new java.sql.Date(convert(date));
Connection conn = null;
Statement stmt = null;
String sql;
try{
System.out.println("Starting try...");
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Connected database successfully...");
// Execute update
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println("Name is " + name +".");
System.out.println("Name is " + getName() +".");
sql = "INSERT INTO spices VALUES (name, 'location', 'container', 'status', useDate)";
stmt.executeUpdate(sql);
// Clean-up environment
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
System.out.println("errors for JDBC");
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
System.out.println("errors for Class.forName");
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
System.out.println("SQLException - stmt.close()");
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
System.out.println("SQLException - conn.close()");
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
server log showing println output:
2015-05-25 19:37:46 Commons Daemon procrun stdout initialized
Starting Update
Starting try...
Connecting to database...
Connected database successfully...
Creating statement...
Name is chilli.
Name is chilli.
Goodbye!
Table output:
| NULL | location | container | status | NULL |
The first NULL should say "chilli".
Any help would be greatly appreciated - I'm tearing hair here!
kwl

It should be
sql = "INSERT INTO spices VALUES ('"+name+"', 'location', 'container', 'status', '"+useDate+"')";

Related

Java and MySQL - "Unrecognized statement"

package main.java;
import java.sql.*;
public class SQLSetup {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test_db";
// Database credentials
static final String USER = "Halli";
static final String PASS = "dragon";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
Why is CREATE TABLE REGISTRATION giving me the error "Unrecognized statement"? I am using Intellij, Java 13 and Maven and MySQL server.
This is just something to get my question through since the template is complaining about me not giving enough details and a lot of code, but I am not sure what more to say about the problem.
It did not even occur to me that I could run the code with Intellij giving me a red error on this, but it did not matter - I tried to run the code and Voila - it created a table, even with this error message.

Hello there, java/database near where syntax error

Everytime i try to update it says - near "WHERE":syntax error. I have successfully been able to update other parts of the classes in the program but this somehow gives me this error.
I think the problem lies here:
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"',"
+ "WHERE userID="+ accid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
Here's the whole code just in case;
public void update_account(){
try { //start or try
//1)create a connection variable
Connection con;
//2)create an instance of the database class
Database db=new Database();
//3)pass the connection from DB to con
con=db.open_connection();
//4)create a statement variable to prepare the SQL
Statement statement=con.createStatement();
//5)create a query to insert the records
String query="UPDATE tblUsers SET fullname='" + txtFullname.getText()+"',"
+ "username='" + txtUsername.getText()+"',"
+ "password='" + txtPassword.getText()+"',"
+ "WHERE userID="+ accid +"";
//6) execute the SQL code
if(statement.executeUpdate(query)==1) { //query was successful
JOptionPane.showMessageDialog(null, "Reference successfully updated!");
//clear the inputs
new MainInterface(user);
frmAccountSett.dispose();
}
}//end of try
catch (Exception e){//start of catch
//display the error
JOptionPane.showMessageDialog(null,e.getMessage());
}//end of catch
}//end of save_recipe()
For sql table update, the syntax is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Notice that there is no comma before the where keyword. In your code, you are adding the comma before your WHERE keyword leading to the error

Inserting value into a single column in MySQL using Java

i'm a novice programmer and following is a part of my code to insert data into the database whose name is book_details.
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO issue_details VALUES("+BookIDvar+",'"+StudentIDvar+"','"+StudentNamevar+"')";
stmt.executeUpdate(sql);
sql = "INSERT INTO book_details (book_status) VALUES ('notavailable') WHERE book_id = "+BookIDvar+"";
// there are 4 fields in the database. I wish to insert the string 'notavailable' into the 4th field which is named book_status for a particular BookID
stmt.executeUpdate(sql);
//STEP 6: Clean-up environment
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
Here i intend to update the status of a library book available and not available. I prefer non - Boolean value for some other reasons.
After the execution the book_details database is not updated. It also gives an error
MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server .
Is there something wrong with the Sql statement or is it something else? Other operations on the same database in other locations are working fine.
This SQL syntax is wrong:
INSERT INTO <table> VALUES <values> [WHERE <whatever>]
You cannot add a WHERE in an INSERT like that.
The only case to add a WHERE statement in an INSERT would be when inserting data from the result of a SELECT statement and the WHERE is part of the SELECT. For example:
INSERT INTO <table> [SELECT <columns> FROM <tables> WHERE <conditions>]
In this form, the columns obtained in the SELECT must match with the values to insert in the table.
Looks like you want to update the status of the book. You should use UPDATE statement instead of INSERT:
UPDATE <table> SET (<column> = <value>) (supports multiple columns) WHERE <conditions>
Applying this to your context, the statement should be:
UPDATE book_details SET book_status = 'notavailable' WHERE book_id = ?
Also, since this is an all or nothing transaction, you should open the transaction and commit if all the statements where executed successfully, otherwise perform a rollback. Here's how you may do it:
try {
conn.setAutoCommit(false);
//perform the DML statements
//...
//commit the transaction
conn.commit();
} catch (Exception e) {
//in case of error, rollback the transaction
conn.rollback();
//notify the error
e.printStacktrace();
} finally {
//ALWAYS close the connection here
//handle the exceptions and such
conn.close();
}
Note that when you need to pass arguments to your SQL statements, you should use PreparedStatement instead of Statement since concatenating the query could lead to SQL Injection attacks. The code should look like:
sql = "INSERT INTO issue_details VALUES(?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, BookIDvar);
pstmt.setString(2, StudentIDvar);
pstmt.setString(3, StudentNamevar);
pstmt.executeUpdate();
//similar for other SQL statements
More info:
Difference between Statement and PreparedStatement
As Luggi mentioned that is incorrect.
update book_details set book_status = 'notavailable' where book_id = bookIDvar;
assuming it already exists in the table.
If not,
insert into book_details (book_id, book_status) values (bookIDvar, 'notavailable');

Unable to fix the error while inserting records into database using JDBC

public class StudentDataPersistence {
public void insertStudentInfo(Student student) {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String username = "system";
String password = "Data03#";
Connection connection = null;
//Statement statement = null;
try {
//Step 1 : Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Step 2 : Open a connection
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
System.out.println("Connected to oracle");
}
//Step 3 : Write code to map Java Object to the Student_Info table
System.out.println("Inserting records into the database");
statement = connection.createStatement();
String sql = "insert into Student_Info " +
"VALUES(student.getName(),student.getRoll_no(),student.getAddress(),student.getPhone_no())";
statement.executeUpdate(sql);
System.out.println("Inserted student information into the database");
} catch (SQLException se) {
//handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
//Handle errors for Class.forName
} finally {
System.out.println("Inside the finally block");
//finally block used to close resources
try {
statement.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("!GoodBye");
}
public static void main(String[] args) {
Student student = new Student("Bavin", 1, "Umar Nagar", "89898989809");
StudentDataPersistence obj = new StudentDataPersistence();
obj.insertStudentInfo(student);
}
}
The error it shows it :
Connecting to a selected database...
Connected to oracle
Inserting records into the database
java.sql.SQLException: ORA-00904: "STUDENT"."GETPHONE_NO": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:189)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:242)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:554)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1478)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:888)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2076)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1986)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2697)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1035)
at org.core.hibernate.reason.StudentDataPersistence.insertStudentInfo(StudentDataPersistence.java:52)
at org.core.hibernate.reason.StudentDataPersistence.main(StudentDataPersistence.java:80)
Inside the finally block
!GoodBye
All the answers (those of you who illustrate it with an oracle query) in reply were wrong.
Kindly do have a look at it before posting.
the correct one i got when i posted another thread regarding the same:
String query = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+student.getName()+"',"+student.getRoll_no()+",'"+student.getAddress()+"','"+student.getPhone_no()+"')";
you have commented out your Statement object definition. So the statement object is unknown when you're using it.
uncomment this line:
//Statement statement;
And as earlier pointed out by #putaro, you need to quote certain parts of your SQL query.
String sql = "insert into Student_Info " +
"VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
This is to insert the actual object values into the query. Things within the quote would be inserted as it is.
Error ORA-00904 means Oracle does not know the identifier "STUDENT"."GETPHONE_NO" it looks like you are trying to insert some value to a column named "GetPhone_NO" to Table "Student" from your SQL. so you should check your SQL and table structure again
I see there are two problems in the code.
Currently your code is not using the student object while making the query. All student.getName() etc call taken as plain strings rather than method calls that returns the appropriate values.
Second it would be better to write the query in the following form. It will avoid silly errors because of the structure of the tables.
"INSERT INTO student_info(name,roll_no,address,phone) VALUES("+
student.getName()+"," +
student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
Even better is if you use prepared statement like
Try changing the query like
"INSERT INTO student_info(name,roll_no,address,phone) VALUES(?,?,?,?)"
and then set the parameter values.

Java and SQLite: Throwing ResultSet closed but proceeding

I've got a following problem: I'm trying to insert data (in this case a username) into a table using the following code:
void AddNewUser(String name, Connection conn){
if(ret == null){
ret = new DB_Retriever(conn);
}
if(!ret.UserExists(name, conn)){
try{
Statement stm = conn.createStatement();
stm.executeUpdate(DB_OperationalData.insert_new_user[0][0] + name + DB_OperationalData.insert_new_user[0][1]);
stm.executeUpdate(DB_OperationalData.insert_new_user[1][0] + name + DB_OperationalData.insert_new_user[1][1]);
stm.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
By the way: It absolutely doesn't matter what I put in the catch clause, nothing that I put there is executed. Just to make everything clear, here is the content of the DB_OperationalData.insert_new_user String array:
public static final String[][] insert_new_user = {
{"INSERT INTO User (Username, Status) VALUES ('","','IN');"},
{"INSERT INTO Statistics (Player_ID) SELECT ID FROM User WHERE Username='","';"}};
The second statement is supposed to copy the ID of the user that is inserted and put it into Player_ID field of the Statistics table (Table User's ID is an autonumbered field).
The exception I get is:
Error while processing the query: java.sql.SQLException: ResultSet closed
What is interesting, is that it works and the data is added correctly but I simply do not want any exceptions thrown.
That's the console output I get:
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
All the lines above the Exception are my own printouts, so I know what has actually happened.
[EDIT]
I have changed the code to use the PreparedStatement instead of ordinary Statement and the current try clause looks as follows:
PreparedStatement pstm = conn.prepareStatement(DB_OperationalData.insert_new_user[0]);
pstm.setString(1, name);
pstm.addBatch();
conn.setAutoCommit(false);
pstm.executeBatch();
conn.setAutoCommit(true);
pstm.close();
And the output is (still regardless of the contents of the catch clause):
This is 'data' Package Testing class
Connection to the database established.
The number of tables existing in the database is: 0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:173)
at org.sqlite.PrepStmt.setString(PrepStmt.java:254)
at data.DB_Writer.AddNewUser(DB_Writer.java:28)
at data.DataHandler.AddNewUser(DataHandler.java:94)
at data.Tester.main(Tester.java:18)
All the queries have been processed successfully
Adding new users:
Error while processing the query: java.sql.SQLException: ResultSet closed
[EDIT 2]
With regards to the original version, when I remove the stm.close(); there is absolutely no difference and I still get the 'ResultSet closed' Exception.
[EDIT 3]
Here is the code of the method that is calling the above:
public void AddNewUser(String username)throws IllegalUsernameException{
if(username.length()==0 || username.length()>20){
throw new IllegalUsernameException();
}
writer.AddNewUser(username, conn);
}
The connection to the database is established by this class:
class DB_Connection {
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName("org.sqlite.JDBC");
}
catch(ClassNotFoundException e){
log("Error while loading the database driver: " + e);
return null;
}
try{
conn = DriverManager.getConnection("jdbc:sqlite:database.db");
}
catch(SQLException e){
log("Unable to connect to the database: " + e);
return null;
}
return conn;
}
public static void log(String msg){
System.out.println(msg);
}
}
The DB_Retriever's method that is checking for the existing username:
boolean UserExists(String name, Connection conn){
String result = "";
try{
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(DB_OperationalData.user_exists[0] + name + DB_OperationalData.user_exists[1]);
result = rs.getString("Username");
}
catch(SQLException e){
System.out.println("Error while processing the query: " + e);
}
if(result.equals(name)){
return true;
}
return false;
}
The only location where Error while processing the query: java.sql.SQLException: ResultSet closed could be printed to the console is in UserExists(..), unless there is another method with a similar catch block. Indeed the ResultSet is not used correctly in UserExists, what may cause the error.
For a more complete description of how to work with JDBC look at this answer or the JDBC documentation. A possible alternative to the existing UserExists is:
boolean userExists(String name, Connection conn) {
PreparedStatement stmt = null;
try{
stmt = conn.prepareStatement("SELECT COUNT(Username) FROM User WHERE Username = ?");
stmt.setString(1, name);
ResultSet rs = stmt.executeQuery();
rs.next(); // set cursor to first row
int count = rs.getInt(1);
rs.close();
return count > 0;
} catch(SQLException e) {
// propagate error
throw new RuntimeException(e);
} finally {
// clean up resources
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ignore) {
log("error on sql clean up", ignore);
}
}
}
}

Categories