I am trying to use sqlite with java application where I am using maven and java8.
Through my application I am able to create database and tables. But when I am trying to do select query It is throwing exception on PreaparedStatement.
Note:
My DB is in D:/Clients/Client1/sqlite/clientDb.db
public boolean testSelectQuery(String val1, String val2) {
String sql = "SELECT *FROM test_table WHERE col1 = ? and col2 = ? ";
Connection connection = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
try {
connection = DriverManager.getConnection("jdbc:sqlite:D:/Clients/Client1/sqlite/clientDb.db");
pstmt = connection.prepareStatement(sql);**// Throwing exception**
// set the value
pstmt.setString(1, val1);
pstmt.setString(2, val2);
rs = pstmt.executeQuery(sql);
return rs.isBeforeFirst();
} catch (SQLException e) {
return false;
} finally {
//close resources
}
}
tried adding database name before table like database.table_name but it's also not working and I saw multiple question on but my issue is not resolved
I have a SQL code in a java code which looks like this :
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
beforeExerTestDTO dto = new beforeExerTestDTO();
StringBuffer sql = new StringBuffer();
sql.append(" select * ");
sql.append(" from n_before_exer ");
sql.append(" where id=?");
sql.append(" and reg_date = (select max(reg_date) from n_before_exer where id=?)");
try {
con = pool.getLocalConnection();
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, id);
pstmt.setString(2, id);
System.out.println("여기까진 살까??");
rs = pstmt.executeQuery();
/......
...... some code /
}catch(SQLException e){
System.out.println("read : " + e);
System.out.println("read : " + sql);
}catch(Exception e){
System.out.println("read : " + e.getStackTrace().toString());
}finally{
DBClose.close(con, pstmt, rs);
}
return dto;
}
When the file gets executed it forms a statement like this in console:
select * from n_before_exer where id=? and reg_date = (select max(reg_date) from n_before_exer where id=?)
and throws a
java.sql.SQLEXCEPTION
What I tried :
I ran the same in Mysql Workbench query :
and got the following error:
Error Code: 1064. 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 '? and reg_date = (select max(reg_date) from
n_before_exer where id=?)' at line 1
A bit of research on the topic shows :
This way is not a preferred way as it can lead to injection attacks
And was advised to use a placeholder for a parameter
It seems a bit complex for me, if anyone can help me construct this statement in the right preferred way please
Thanks
You should be using a prepared statement:
Connection con; // get a connection
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, someInt);
ps.setInt(2, someOtherInt);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
// process each record
}
Your statement seem correct in syntax. Are you have encoding issue on you java file?
pstmt.setString(1, id);
I guess the problem is that the type of id is not string ,you could use this to have a try:
whats wrong with my codes? I think its in the SQL but I don't know why. thank you in advance
try{
clsConnect c = new clsConnect();
Connection conn = c.makeConnection();
Statement statement = conn.createStatement();
String display = "SELECT SUM(Amountpaid) from mofficetbl";
ResultSet rs = statement.executeQuery(display);
while(rs.next()){
totalTF.setText(rs.getString("Amountpaid"));
}
}
catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
when you call this select statement; the returned column is actually called "SUM(amountpaid)" and not amountpaid so either change its alias with
"SELECT SUM(Amountpaid) as Amountpaid from mofficetbl"
You can also do:
rs.getString("Sum(Amountpaid)");
You are selecting SUM(amountpaid) and trying to access the column amountpaid, but that column doesn't actually exist in the ResultSet Try rs.getString(1) or giving the SUM a name in the select as SELECT SUM(amountpaid) as sum from msofficetbl then doing rs.getString("sum");
I'm trying to insert a new record into an MS SQL database, and I'm getting an exception I've never seen before. When I call executeUpdate the following exception is thrown:
com.microsoft.sqlserver.jdbc.SQLServerException: A result set was generated for update.
This is the Java code that produces the error:
// addComment method adds a new comment for a given requestId
public CommentBean addComment(CommentBean comment) {
PreparedStatement stmt = null;
INative nat = null;
Connection conn = null;
try {
nat = dbConn.retrieveNative();
conn = (Connection)nat.getNative("java.sql.Connection");
stmt = conn.prepareStatement(ADD_COMMENT);
stmt.setInt(1, comment.getRequestId());
stmt.setString(2, comment.getComment());
stmt.setString(3, new SimpleDateFormat("MM/dd/yyyy").format(comment.getDateCreated()));
stmt.setString(4, comment.getCreatedBy());
comment.setCommentId(stmt.executeUpdate()); // exception
} catch(Exception ex) {
System.err.println("ProjectRegistration::SQLDAO - addComment");
ex.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (Exception e) {}
}
return comment;
}// end addComment
Where ADD_COMMENT is defined as a String:
private static final String ADD_COMMENT = "INSERT INTO RequestComments OUTPUT INSERTED.commentId VALUES(?,?,?,?)";
For the sake of being thorough, the table is defined as:
CREATE TABLE RequestComments (
commentId int NOT NULL PRIMARY KEY IDENTITY(1,1),
requestId int FOREIGN KEY REFERENCES Requests(requestId),
comment varchar(400),
dateCreated date,
createdBy varchar(12)
);
I don't think I'm doing anything terribly complicated here, but I can't think of why I'm getting this exception. I have a method in the same class which does the exact same type of insertion (literally the same query with a different table name and number of values), and it has no issues. Does anyone have any ideas on how to resolve this issue?
This particular error can also be caused by an INSERT-trigger, which has a SELECT-statement as a part of the trigger code.
To test whether this is the case, you can try:
using executeQuery(), instead of executeUpdate() - and display the result.
executing the insert in tool like MySQL Workbench, SQL Server Management Studio, or whatever flavour of database design tools are available for your DBMS, to see whether a result is returned.
Related: sql server error "A result set was generated for update"
I'm hoping this may help others looking at the same error message, as it did for me. My solution was to live with a call to executeQuery(), although it only handles an underlying issue, instead of fixing it.
This instruction stmt.executeUpdate() is not returning the commentId, it returns a ResultSet which you could then get the commentId from. Something like this,
ResultSet rs = stmt.executeQuery(); // Not update, you're returning a ResultSet.
if (rs.next()) {
comment.setCommentId(rs.getInt(1));
}
you are using OUTPUT in your insert query i.e you will get a resultset after your query executes and to hold that you need an object of class ResultSet to hold that data
SqlServer : When SET NOCOUNT is ON, the count is not returned. When SET NOCOUNT is OFF, the count is returned.
Connection conn = DriverManager.getConnection(connectDB,user,pwd);
String sql = " set nocount off;INSERT INTO test (name) values (1)";
PreparedStatement prepareStatement = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
System.out.println(prepareStatement.executeUpdate());
ResultSet generatedKeys = prepareStatement.getGeneratedKeys();
if(generatedKeys.next()){
System.out.println(generatedKeys.getString(1));
}
Related:
set-nocount-on-usage
I've had a similar problem where after a while an insert on a autonumber table would give a "A result set was generated for update." at random. I use connection pooling and somehow the driver can get into a state where executeUpdate in combination with Statement.RETURN_GENERATED_KEYS doesn't work anymore. I found out that in this state an executeQuery does the trick, but in the initial state executeQuery does not work. This lead me to the following workaround:
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO XYZ (A,B,C) VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = null;
try {
psInsert.setString(1, "A");
psInsert.setString(2, "B");
psInsert.setString(3, "C");
Savepoint savePoint = connection.setSavepoint();
try {
psInsert.executeUpdate();
rs = psInsert.getGeneratedKeys();
} catch (SQLServerException sqe)
{
if (!sqe.getMessage().equals("A result set was generated for update."))
throw sqe;
connection.rollback(savePoint);
rs = psInsert.executeQuery();
}
rs.next();
idField = rs.getInt(1);
} finally {
if(rs != null)
rs.close();
psInsert.close();
}
I am using the following code to update my mysql table where both moving50 and moving200 are variable characters.
String sql = "update toplosers set Moving50 = ?, where Symbol = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
for(int i1=0;i1<i;i1++)
{
stmt.setString(1, moving50[i1]);
stmt.setString(2,symbol[i1]);
stmt.addBatch();
}
stmt.executeBatch();
}
I am getting "have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where Symbol = 'mysymbol'' at line 1
What is the problem
You have unexpected comma right after first parameter.
No need to add 'comma' for where clause.
Now check it.
String sql = "update toplosers set Moving50 = ? where Symbol = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
for(int i1=0;i1<i;i1++)
{
stmt.setString(1, moving50[i1]);
stmt.setString(2,symbol[i1]);
stmt.addBatch();
}
stmt.executeBatch();
}
see sample example here
Avoid the comma character before the 'where' clause.