JDBC query insert with special character ("\N", "\S" and "\T") - java

I have raw insert query like
insert into sample(id, name) values(1, 'text \\N\');
Getting SqlException while trying to insert via jdbc but the same insert query is working if I insert via mysql command prompt(console).
jdbc insert query is failing due to special characters("\N") in name field.
so how to overcome and insert the name with \N?

The cleanest approach is to not use a raw SQL query at all. If, as you've stated, you receive the name from some other process then it is presumably in a String variable (or property, or similar) so you can simply use a parameterized query to perform the insert:
// example data
int theId = 1;
String theName = "the name you received from somewhere else";
//
PreparedStatement ps = conn.prepareStatement("INSERT INTO sample (id, name) VALUES (?, ?)");
ps.setInt(1, theId);
ps.setString(2, theName);
ps.executeUpdate();

Related

OR clause in prepared statement java

Can we use OR clause in a PreparedStatement using java?
PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setString(1, "'MIKE' || 'ANDY'");
int i = stmt.executeUpdate();
System.out.println(i + " records deleted");
You can simply use two parameters.
PreparedStatement stmt=con.prepareStatement("delete from emp where id=? or id=?");
stmt.setString(1,"ANDY");
stmt.setString(2,"MIKE");
No. This is not raw text substitution and you can’t drop in chunks of the query and expect them to get incorporated in. Each thing substituted for a placeholder gets sanitized, encoded, and quoted as a separate value.
But you can write it with 2 placeholders:
PreparedStatement stmt=con.prepareStatement(
“delete from emp where id in (?, ?)”);
stmt.setString(1,"MIKE”);
stmt.setString(2, “ANDY”);
If you have a lot of values in the IN clause an alternative is to put those values in a table and join to it.

Oracle query inside java

String sql = "INSERT INTO Student_Info(name,roll_no,address,phone_no) VALUES('101', 1, 'Fatma', '25')";
String sql = "insert into Student_Info(name,roll_no,address,phone_no) VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
the last query shows an error:
java.sql.SQLException: ORA-00917: missing comma
at
statement.executeUpdate(sql);
Can anyone rule out where am I missing the comma?
You miss the single quotes around student.name, student.address and student.phone_no
String sql = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+
student.getName()+"',"+
student.getRoll_no()+",'"+
student.getAddress()+"','"+
student.getPhone_no()+"')";
Do notice that this sql statement is vulnerable for sql injection attacks. Use a PreparedStatement.
String sql = "insert into Student_Info(name,roll_no,address,phone_no) " +
"VALUES(?,?,?,?)";
addStudent = con.prepareStatement(sql);
addStudent.setString(1, student.getName());
addStudent.setInt(2, student.getRoll_no());
addStudent.setString(3, student.getAddress());
addStudent.setString(4, student.getPhone_no());
addStudent.executeUpdate();
con.commit();
Do it in this way:
String sql = "insert into Student_Info(name, roll_no, address, phone_no)
VALUES(?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, value); // indexing starts from 1 (not from zero)
...
ps.executeUpdate();
// commit if you have set auto-commit to false
Never use raw statements but PreparedStatements1. Raw statements have lower performance, are more vulnerable (SQL Injection attacks) and what is most important is readability of code that is on very low level (especially in case if you have more columns).
1PreparedStatements are much more safer, pre-compiled, have better performance and are user-friedly readable and more...
rene's answer is correct. I would like to add, however:
It is much better practice to use Prepared Statements
Your code would look something like:
String sql = "INSERT INTO Student_Info(?,?,?,?) VALUES(?,?,?,?)"
PreparedStatement sql_prepared = connection_object.prepareStatement(sql)

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);

Insert new data into specific table in a the database

I design a system and I want from the user firstly to choose from a combo box the name of the table he want to insert then he will enter the rest of the fields.. My question is that how can I let the user enter the name of the table using sql statement .. I write the following doesn't but it doesn't work ??
try {
Object service = Service_ComboBox.getSelectedItem();
String ref = "0";
String title = title_TextField1.getText();
Object riskRating = riskRating_ComboBox3.getSelectedItem();
Object rootCause = rootCause_ComboBox4.getSelectedItem();
Object impact = impact_ComboBox1.getSelectedItem();
Object likelihood = likelihood_ComboBox2.getSelectedItem();
String efforts = efforts_TextField7.getText();
String finding = finding_TextField9.getText();
String implication = implication_TextArea1.getText();
String recommendation = recommendation_TextArea2.getText();
Connection conn= DriverManager.getConnection ("jdbc:oracle:thin:#localhost:1521:XE","SYSTEM","*******");
String query = "insert into ? (Service,Ref,Title,Risk_Rating,Root_cause,Impact ,Likelihood,Efforts,Finding,Implication,Recommendation)values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? , ?)";
PreparedStatement myStatment = conn.prepareStatement(query);
myStatment.clearParameters();
myStatment.setString(1, service.toString());
myStatment.setString(2, service.toString());
myStatment.setString(3, ref);
myStatment.setString(4, title);
myStatment.setString(5, riskRating.toString());
myStatment.setString(6, rootCause.toString());
myStatment.setString(7, impact.toString());
myStatment.setString(8, likelihood.toString());
myStatment.setString(9, efforts);
myStatment.setString(10, finding);
myStatment.setString(11, implication);
myStatment.setString(12, recommendation);
boolean myResult = myStatment.execute();
System.out.println("done");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, "Information is missing or incorrect! Please Make sure to enter correct information");
Logger.getLogger(Insert_info.class.getName()).log(Level.SEVERE, null, ex);
return;
}
JOptionPane.showMessageDialog(this, "Your information was saved successfully!");
insert into ?
You cannot use a bind variable for schema object names. The reason being that when you prepare the statement, the database needs to know what tables are involved, and decide which indexes to use, so the query SQL needs to be known (only the data can change).
So if you want to do this, you have to use string interpolation to construct the query (only for the table name, continue to use bind variables for the data!).
String query = "insert into "+ tableName + ....
Make sure that you validate this tableName. In your case, it can probably be checked against a HashSet of valid table names. Do not let this become an SQL injection problem.
Use the folowing sintax:
String query = "insert into " &tablename "bla bla predicates"
To avoid the sql injection create roles in your databases and give access to the tables you want to be used by your visitors/users.
Or you can use a wildcard :
Create a Variable tbl_name
String query = "insert into "(select table_name from user_tables where table_name like '%tbl_name%')"<br/>
- next create a decision "IF" and throw the output of the wildcard in it.If it matches the tables you have then ok if not treat it with an error message.

JDBC - How to insert a string value

When trying to insert the value of a string into my db using JDBC instead of inserting the String's value it inserts the String's name.
I have a string named firstName, the value of this string is given by user input.
Here is my sql statement:
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','+firstName()','123')";
For various reasons, it is better to use java.sql.PreparedStatement. to execute statements with parameters. For example, if you want to avoid sql injection attacks.
See the examples in Using Prepared Statements from The Java Tutorials.
The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.
PreparedStatement pstmt = conn.prepareStatement(
"UPDATE EMPLOYEES SET FIRST_NAME= ? WHERE ID = ?");
pstmt.setString(1, "user1080390"); // set parameter 1 (FIRST_NAME)
pstmt.setInt(2, 101); // set parameter 2 (ID)
int rows = pstmt.executeUpdate(); // "rows" save the affected rows
Try this
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','"+firstName()+"','123')";
To prevent sql injections, you need to escape the string before using in a query or try the prepared statements.
Something like this..
String firstName ="sample";
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124',"+firstName+",'123')";

Categories