sql query exception in java - java

I am trying to connect my java project with database in netbeans. I have a table named task_table and i'm trying to add some values on that table.
Here is my code
Connection con1;
PreparedStatement insert;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String name1= addtaskname.getText();
String name2= addtaskdate.getText();
String name3= addtasktime.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/jesin_virtual","root","");
insert = con1.prepareStatement("insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)");
insert.setString(1, name1);
insert.setString(2,name2 );
insert.setString(3,name3);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Task Added sucessfully");
and i got this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax

The problem is here:
insert into task_table(Task Name,Task Date,Task Time) values (?,?,?)
^ ^ ^
If the column names really contain blanks, then you need backticks around the names (`Task Name`), else change the names to what they really are (Task_Name maybe?).

Please correct SQL query inside as below...
if in your database column names contains space so please use below query
"insert into task_table("Task Name","Task Date","Task Time") values (?,?,?)"
if in your database column names contains _ so please use below query
"insert into task_table(Task_Name,Task_Date,Task_Time) values (?,?,?)"

Related

Java JDBC program throwing SQL syntax error when fetching particular rows from a table

I have a database called 'airplane' inside which there is a table named timetable . The timeatable table has a column fromcity of text type
Connection conn0=null;
PreparedStatement st0=null;
String sql0="SELECT FROM timetable where fromcity=?";
try{
Class.forName("com.mysql.jdbc.Driver");
conn0=DriverManager.getConnection(DB_URL,USER,PASS);
st0=conn0.prepareStatement(sql0);
st0.setString(1,city[i]);
ResultSet rs0=st0.executeQuery();
if(rs0.next())
{
System.out.println("flight exists");
}
else
{
System.out.println("fight does not exist");
}
}
catch(Exception et)
{
System.out.println("Error"+et.getMessage());
}
I am getting the error:
why am I getting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM timetable where fromcity='1'' at line 1
You forgot to write column names in your query.
Make it,
SELECT * FROM timetable where fromcity=?"
instead of,
SELECT FROM timetable where fromcity=?"

inserting a row of data in sql server 2014 in javafx

i want to insert a row of data into my USERS table...
this is my code
#FXML
private void handleRegisterButtonAction() throws SQLException{
String userName="'"+txt_username.getText()+"'";
String password="'"+txt_password.getText()+"'";
String mail="'"+txt_userMail.getText()+"'";
//for example user id is 22
int userId=22;
String insertUser="INSERT INTO USERS(userId,userName,userPassword,userEmail)"
+ " VALUES("+userId+","+userName+","+password+","+mail+");";
stmt.execute(insertUser);
}
the code runs but table in the database doesn't change
this is because sql doesn't know to apply this query on which database!
But i dont know how to solve this
Write query like this :
INSERT INTO **Database_Name**.dbo.USERS(userId,userName,userPassword,userEmail)"
+ " VALUES("+userId+","+userName+","+password+","+mail+");";
Change Database_Name to your database name, then run your code.
First of all use PreparedStatements because if the userName or password have illegal characters you will have problems with your database .
Example character ' and boom the insert will not work.
PreparedStatement statement = dataBaseConnection.prepareStatement( INSERT INTO '"+tableName+"' (userId,userName,userPassword,userEmail) VALUES(?,?,?,?)");
//Add the data to the table
statement.setInt(1,userId); //better to user autoincrement
statement.setString(2, userName);
statement.setString(3, password);
statement.setString(4,userEmail);
//Execute the update
statement.executeUpdate();
//commit in case you have turned autocommit to false
databaseConnection.commit();
Observe carefully the statement cause you can see on the table name i have ' and ' single column before and after the name of the table.

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException Insert mysql error

This is the whole message I receive:
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 ''user','age','school','password') values ('Admin','22','tei','admin')' at line 1
And this is the code:
String user = textField.getText().trim();
String age = textField_3.getText().trim();
String school = textField_4.getText().trim();
String password = String.valueOf(passwordField.getPassword());
String password1 = String.valueOf(passwordField_1.getPassword());
if(password.equals(password1)){
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","1234");
PreparedStatement st = con.prepareStatement("insert into user ('user','age','school','password') values ('"+user+"','"+age+"','"+school+"','"+password+"')");
int rs = st.executeUpdate();
JOptionPane.showMessageDialog(frame, "Data Saved Successfully");
Any ideas?
The point of prepared statements is, among others, to not concatenate your queries yourself.
You want to do the following:
//first you "prepare" your statement (where the '?' acts as a kind of placeholder)
PreparedStatement st = con.prepareStatement("insert into user (user,age,school,password) values (?,?,?,?);");
//now you bind the data to your parameters
st.setString(1, user);
...
//and then you can execute it
st.executeUpdate()
For more details see the official tutorial.
There are a couple of things happening behind the scenes that make the query safe, like escaping special characters that would otherwise allow altering the statement (google SQL injections if you want to know more)

How to get the Generated insert ID in JDBC?

My source code has the following structure:
SourceFolder
AddProduct.jsp
Source Packages
-Controller(Servlets)
SaveProduct.java
-Model(Db Operations)
ProductDbOperations.java
I am inserting a new product into the product table and at the same time I am inserting an entry into product_collection table (product_id | collection_id).
To insert an entry into the product_collection table i need to get generated id from product table. After that a new entry is inserted into the product_collection table.
Also, I am not using any Framework and am using Netbeans 7.3.
Problem:
A new entry is inserted into the product table with this piece of code
IN: ProductDbOperations.java
try
{
this.initConnection(); // Db connection
pst = cn.prepareStatement("INSERT INTO product values('"+name+"', "+quantity+", "+price+")");
rs = pst.executeUpdate();
}
catch(SQLException ex)
{
}
I Also used the solution at following link which doesn't works for me.
I didn't got any SQL exception
How to get the insert ID in JDBC?
so help me find out why this code not working for me .
Thanks a million.
Not all drivers support the version of getGeneratedKeys() as shown in the linked answer. But when preparing the statement, you can also pass the list of columns that should be returned instead of the "flag" Statement.RETURN_GENERATED_KEYS (and passing the column names works more reliably in my experience)
Additionally: as javaBeginner pointed out correctly, your usage of a prepared statement is wrong. The way you do it, will still leave you wide open to SQL injection.
// run the INSERT
String sql = "INSERT INTO product values(?,?,?)";
pst = cn.prepareStatement(sql, new String[] {"PRODUCT_ID"} );
pst.setString(1, name);
pst.setInt(2, quantity);
pst.setInt(3, price);
pst.executeUpdate();
// now get the ID:
ResultSet rs = pst.getGeneratedKeys();
if (rs.next()) {
long productId = rs.getLong(1);
}
Note that the column name passed to the call is case-sensitive. For Oracle the column names are usually uppercase. If you are using e.g. Postgres you would most probably need to pass new String[] {"product_id"}
The way you are using is not the proper way of using preparedstatement
use the following way
pst = cn.prepareStatement("INSERT INTO product values(?,?,?)");
pst.setString(1,name);
pst.setInt(2,quantity);
pst.setInt(3,price);
pst.executeUpdate();
Yes there is a way to retrieve the key inserted by SQL. You can do it by:
Using Statement.RETURN_GENERATED_KEYS in your previous insert and get the key which can be used in further insert
e.g:
String query = "INSERT INTO Table (Col2, Col3) VALUES ('S', 50)";
Statement stmt = con.createStatement();
int count = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Error inserting query into database with jdbc

in my application I'm trying to insert a query into an oracle database using jdbc. I create this table:
create table TMP
(
SYNC NUMBER,
USER VARCHAR2(50),
DAT DATE
)
And I use this code to insert an entry:
PreparedStatement stat=null;
try {
dbStatement = dbConnection.createStatement();
String sql = "INSERT INTO TMP (USER, DAT) Values (?,?);";
for (ReplicationHistoryDetailVO tmpEntry : entry) {
if (tmpEntry.getSyncPhase() == REPLICATION_PHASE.DOWNLOAD) {
stat=dbConnection.prepareStatement(sql);
stat.setString(1, "David");
stat.setDate(2, new Date(tmpEntry.getFinishTime()));
stat.executeUpdate();
}
}
From this code I have the following error:
Error updating database java.sql.SQLSyntaxErrorException: ORA-00911
The connection is ok. I must to write only two values, because the first value is an autoincremental key and I don't set this. Any ideas?
Try "INSERT INTO TMP (USER, DAT) Values (?,?)" without the ; at the end.
ORA-00911 is a common error for common syntax mistakes.

Categories