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.
Related
I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
There is an error on the line that says ps = stmt.executeQuery();....the error says method executeQuery in interface Statement cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
But whenever I pass a String through that line I get an error saying java.sql.SQLException:Method 'executeQuery(String)' not allowed on prepared statement...
This method is for a button that adds all the Integer values in a column of SQL table.
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
stmt = con.prepareStatement(SQL);
ps = stmt.executeQuery();
if(ps.next()) {
String total = ps.getString("SUM(PRICE)");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
Column name is must while getting a data
Thanks
Updated following the question change
There is no column name explicitly specified for the calculated column SUM(PRICE) in your SQL statement. It would hardly ever actually be "SUM(PRICE)". Try naming your column. Also prepareStatement is useful when passing parameters. Simple Select does not need it:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) As PRICE_TOTAL FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString("PRICE_TOTAL");
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
or access the value by column index rather than name:
private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {
try{
String SQL = "SELECT SUM(PRICE) FROM MENU";
Statement stmt = con.createStatement();
ResultSet ps = stmt.executeQuery(SQL);
if(ps.next()) {
String total = ps.getString(0);
textTotalCost.setText(total);
}
}
catch (SQLException err) {
JOptionPane.showMessageDialog(null, err);
}
}
I don't fully understand your description but I think you are trying to assign the PreparedStatement created in
stmt = con.prepareStatement(SQL)
to a variable of type Statement (stmt) and that's causing the error. The line of code above works because PreparedStatement is an extension (or implementation) of Statement but
ps = stmt.executeQuery();
fails because the class Statement doesn't have an executeQuery method without parameters, PreparedStatement does.
#Y.B.'s solution and the rest of recommendations are good (the alias for sum(price) or getting the value by column index) if it's ok using a regular Statement. The alternative is changing the type of stmt to PreparedStatement in your original code.
package controller;
import pojo.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConn {
int found=0;
public boolean register(Member c)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
System.out.println("Data base is connected");
rs= stmt.executeQuery("select USERID from member");
System.out.println("Hi");
while(rs.next())
{
System.out.println("bye");
if((c.getUserId()).equals(rs.getString(1)) )
{
System.out.println("bye");
found=1;
break;
}
}
if(found==1)
{
return false;
}
else
stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"',,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')");
return true;
}
catch(ClassNotFoundException e)
{
System.out.print(e);
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
public boolean login(String userid, String password)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
rs= stmt.executeQuery("select userid, password from member where userid = '"+userid+"'");
if(rs==null)
{
return false;
}
else
{
while(rs.next())
{
String uid,pass;
uid=rs.getString(1);
pass=rs.getString(2);
if(password.equals(pass))
{
return true;
}
else
{
return false;
}
}
}
}
catch(ClassNotFoundException e)
{
System.out.print(e);
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
}
I am invoking the code from one servlet. It is showing me the following output.Though the same code is working correctly in somewhere else:
Output:
Data base is connected
Hi
java.sql.SQLException: ORA-00936: missing expression
Can anyone help me with the problem.
In your insert you have the following
+c.getAddress1()+"',,'"+c.getAddress2()+
There should be only one comma instead of two
I suggest to use PreparedStatement to avoid such error.
Advantage of using PreparedStatement over Statement
A SQL statement is precompiled and stored in a PreparedStatement object.
This object can then be used to efficiently execute this statement multiple times.
Reduces execution time.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters
Read more PreparedStatements and performance
See Java Tutorial on Using Prepared Statements
sample code:
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, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
Find complete Sample example here to learn more about it.
Use prepared statements to avoid such issues. This will also avoid issues which you may face because of certain special characters like single quotes etc.
If not, then try one of the following:
If there is no column between address1 and address2, then use below (extra comma removed):
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"','"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);
If there is supposed to be an empty value that has to be inserted, then use below (an empty field is inserted using ,'', )
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"', '' ,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);
In your insert statement you can specify which columns you insert/update that would correspond to the SQL syntax having insert into member (col1, col2) values (val1, val2). The number of columns should be exactly the same before and after values in parenthesis. Incorrect number of columns or values are caused the error.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("Connect database in BallMoves1.java .......");
/*the below line giving error*/
rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
System.out.println("Score is inserted..");
System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}
/*highscore is table and attributes of table are (sid,score).
the resulting error is:
Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
at BallMoves1.move(BallMoves1.java:378)
at BallMoves1.run(BallMoves1.java:223)
at java.lang.Thread.run(Thread.java:744)*/
You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:
String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, score);
statement.executeUpdate();
conn.commit();
}
Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.
Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.
I would like to insert data into the MySQL database that I am using.I get this ERROR.This is my code:
public boolean insertValues(String gisuniqkey,String objtype,String objkey,String lat,String lng)
{
int rc=-1;
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
//lots of String concatenation,very expensive...BAD...use StringBuilder instead
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values("+gisuniqkey+","+objtype+","+objkey+","+lat+","+lng+");";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rc>0?true:false;
}
I think the insert statement should be like this, Use single quotes around the values:
"Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Edit
Try it yourself in a command. What will work:
Option 1:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES(asdasd,asdasd,asdasd,asdasd);
Option 2:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES('asdasd','asdasd','asdasd','asdasd');
I would think that option 2 will work
Edit 2
But as mention in the comment. Using the prepare statement is recommended. Because this is open for sql injections
Reference:
SQL injection
JDBC PreparedStatement Example – Insert A Record
You should use PreparedStatements to avoid problems with building query strings.
PreparedStatement statement = null;
String insertSql = "Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values (?,?,?,?,?)";
conn.setAutoCommit(false);
statement = conn.prepareStatement(insertSql);
statement.setString(1, gisuniqkey);
statement.setString(2, objtype);
statement.setString(3, objkey);
statement.setString(4, lat);
statement.setString(5, lng);
con.commit();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Although, I would suggest you inject variable values using prepared statement.