error due to single quotes in insert query - java

I am inserting values in a Mysql database from java file using -
String query = "INSERT INTO genes (sent, title) VALUES ('"+sent+"','"+title+"')";
Statement stmt = con.createStatement();
int rs = stmt.executeUpdate(query);
where sent and title are variable strings extracted after applying some algorithm. But this gives sql error when sent or title contains single qoutes.

Consider using a prepared statement with parameters:
PreparedStatement pstmt = con.prepareStatement(
"INSERT INTO genes (sent, title) VALUES (?, ?)");
pstmt.setString(1, sent);
pstmt.setString(2, title);
pstmt.executeUpdate();

You should use PreparedStatement in fill the query parameters. It takes care of escaping the single quotes if any in the input parameters.
Modify your query and statement object as follows and it should be working:
String query = "INSERT INTO genes (sent, title) VALUES (? , ?)";
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, sent );
pst.setString( 2, title );
int insertResult = pst.executeUpdate();

You should use PreparedStatements for that. PreparedStatement is under java.sql.* namespace.
String insertString = "INSERT INTO genes (sent, title) VALUES (?,?)";
// con is your active connection
PreparedStatement insertX = con.prepareStatement(updateString);
insertX.setString(1, sent);
insertX.setString(2, title);
insertX.executeUpdate();

You should never concatenate SQL statements like this, instead, use prepared statements:
String query = "INSERT INTO genes (sent, title) VALUES (?,?)";
PreparedStatement stmt = con.prepareStatement(query);
p.setString(1, sent);
p.setString(2, title);
p.executeUpdate();
If you use the string concatenation method you are exposing yourself to dangerous sql-injection attacks.

String query = "INSERT INTO genes (sent, title) VALUES (?, ?)";
PreparedStatement pt = con.prepareStatement(query);
pt.setString(1, sent);
pt.setString(2, title);
pt.executeUpdate();

Please, Remove ' from string or replace by \' from '.
Mysql allow only in \' format for special character.

Related

Java - Query does not return results

java.sql.SQLException: Query does not return results
This is the error I get when running my code.
I am making a tic-tac-toe game to run off of a database. I'm making an empty board with this code.
Any ideas of why the database is not being updated??
//INSERT SPACE
String space1 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space2 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space3 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space4 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space5 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space6 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space7 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space8 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
String space9 = "INSERT INTO space(row,column,contents) VALUES (?,?,?)";
/**
* Inserts empty space into space 1
*/
try {
PreparedStatement preparedStatement = connectDatabase.getConnection().prepareStatement(space1);
preparedStatement.setInt(1,0);
preparedStatement.setInt(2,0);
preparedStatement.setString(3, "e");
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
You should use preparedStatement.executeUpdate() instead. See the docs here.
The method .executeQuery() is only used for SELECT operations, or in general for any queries that return something. If, instead, you want to modify your database, you must use .executeUpdate() instead.
ResultSet resultSet = preparedStatement.executeUpdate();
^^^^^^
ExecuteUpdate is the method to use for non-results-returning DML.

Number of columns for result set error in SQL database for Java app

I'm having an issue with adding data to a sql database through Java on Netbeans.
String bladeSerial;
String bladeType;
LocalTime startTime1;
private void startButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println ("Successful Connection");
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
I get the error The column position '1' is out of range. The number of columns for this ResultSet is '0'.
In the database, Serial is VARCHAR(5), Bladetype is VARCHAR(80)and StartT1 is VARCHAR(12)
The startTime1 variable is saved in the format HH:mm:ss.SSS.
I appreciate any help on this error
You need to give placeholder in your query. Change your code as given here...
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
You don't need to give column names in query when you are using Prepared statement. Do the following changes:
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
Hope it helps!!
Here you are forming query like simple statement and used it in prepared statement which is not possible, so change your query with place holder like below.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
If you want to directly use variables names like bladeSerial, then you should use these String variables as if you're adding multiple Strings.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ("+bladeSerial+", "+itemText+", "+(String.valueOf(startTime1))+")";
But this is strictly not recommended as it would introduce serious security issues.
The recommended way is to use PreparedStatement. The query you've written is correct, it's just that you have to use placeholders instead of variable names.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}

How to use java variable to insert values to mysql table?

Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

Adding to table using Jdbc & ms managment system

I bumped into this problem and i cannot figure out what is wrong with this code. I use jdbc and ms managment system for the databse and its connection.
code:
try {
//create user
preparedStatement = conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
rs = preparedStatement.executeQuery();
System.out.println(rs.toString());
catch (Exception e) {
System.out.println("Exception: " + e);
}
error:
Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '='.
The way you are using the ? characters is invalid in JDBC:
"INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)
One ? represents the whole bind variable. Try
"INSERT INTO Users(name, pass, type) VALUES (?, ?, ?)"
Also, use executeUpdate to execute an insert statement (or update, or delete).
Remove the field names from the value list. These are already in the name list. Also use executeUpdate for database write operations:
preparedStatement =
conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (?,?,?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
int rowCount = preparedStatement.executeUpdate();

Can i execute query and sql function in same statement?

I have a PreparedStatement and CallableStatement:
String sql = "INSERT INTO parcels (cadastr,the_geom,status_id) VALUES(?,PolygonFromText(?, 4326),?)";
PreparedStatement stmt = ce.prepareStatement(sql);
stmt.setString(1, ts.getPackage().getSpecifyParcels().getExistParcel()
.get(0).getCadastralNumber());
stmt.setString(2, WKT);
// stmt.setString(3, deleted);
stmt.setInt(3, status_id);
stmt.execute();
stmt.close();
java.sql.CallableStatement proc1 = ce
.prepareCall("{call insert_into_wgs()}");
proc1.execute();
proc1.close();
Its possible to execute this query and function insert_into_wgs() in one statement?
Use the RETURNING keyword!
INSERT INTO parcels (cadastr,the_geom,status_id)
VALUES (?, PolygonFromText(?, 4326), ?)
RETURNING insert_into_wgs()

Categories

Resources