JDBC - Resultset is false - sql

I have the following problem.
I'm using JDBC and doing a query. But the qry doesn't work. If I let print out rs.next() it returns false.
The same qry works on the SQL-Developer itself, just not in JDBC.
QRY:
ResultSet rs = stmt.executeQuery("select account_id, oper_type, new_value from action where account_id = 1");
//ResultSet rsAccount = stmt.executeQuery("select account_id from accounts");
System.out.println("Accounts Update");
System.out.println(rs.next());
if(rs.next() == true){
System.out.println("Not null");
}

Ok, I "solved" it. The problem was that my project tutor forgot to add commit; at the end of the sql file

Related

Pass SELECT MAX(`Id`) FROM Table to setval()

I want to pass (SELECT MAX(Id) FROM Table to mariadb's setval() function I tried with:
SELECT setval(`MySequence`, (SELECT MAX(`Id`) FROM `Table`));
but it doesn't work, I also tried:
SET #max_value = (SELECT MAX(`Id`) FROM `Table`);
SELECT setval(`MySequence`, #max_value);
how am I supposed to do this?
EDIT I made a mistake posting the question. I was using SET on the second code and is not working
EDIT As I said on the comments I'm trying to do this just once, executing from an Entity Framework Core migration. What I ended doing is executing the SELECT MAX(Id) FROM Table and recovering that value from the migration code to interpolate it later on the $"SELECT setval('sequence', {value}, true)"
I found working workaround using prepared statement:
SET #max_value = (SELECT MAX(`Id`) FROM `Table`);
EXECUTE IMMEDIATE CONCAT('SELECT SETVAL(`MySequence`, ', #max_value, ')');
In a select, use := to assign variables:
SELECT #max_value := MAX(`Id`) FROM `Table`;
SELECT setval(`MySequence`, #max_value);
You might want to add 1 to the value.
I think you can do:
SELECT setval(`MySequence`, MAX(Id))
FROM `Table`;
In a stand-alone statement (not a query), SET is generally used to assign value to a user-defined variable. Try the following instead:
SET #max_value = (SELECT MAX(`Id`) FROM `Table`);
SELECT setval(`MySequence`, #max_value);
It seems that is not possible to do this as of MariaDB 10.3.16
I've raised a bug on https://jira.mariadb.org/browse/MDEV-20111 for devs to consider adding this feature or upgrading the documentation to make explicit that it can't be done.
I worked arround this by selecting the value using the Mysqlconnector in c# code
private long ReadMaxIdFromTable()
{
MySqlConnection connection = null;
try
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var builder = new ConfigurationBuilder();
var builderenv = builder.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile($"config/appsettings.{environment}.json", false, false).AddEnvironmentVariables();
IConfigurationRoot configuration = builderenv.Build();
var connectionString = configuration.GetConnectionString("ConnectionStringName");
connection = new MySqlConnection(connectionString);
connection.Open();
var cmd = connection.CreateCommand() as MySqlCommand;
cmd.CommandText = #"SELECT MAX(`Id`) FROM `Table`";
var result = (long)cmd.ExecuteScalar();
return result;
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null && connection.State != System.Data.ConnectionState.Closed)
{
connection.Close();
}
}
}
Is not as clean as I would like it but, it gets the job done.
Later I use SETVAL interpolating the value in the sql string again from c# code.
var currentSeq = ReadMaxIdFromTable();
migrationBuilder.Sql($"SELECT SETVAL(`MySequence`, {currentSeq}, true);");
Also, beware that all the Up() code it's executed BEFORE anything gets to the database, this means that SELECT MAX(Id) FROM Table; has to result in the value we're looking for before the migration starts manipulating the database.

JSP SQL SERVER ResultSet always return empty

I'm doing two queries to a SQL Server database, the first query returns the Result Set with data, but the second query always returns the Result Set empty. If I do the query in the SQL SERVER, it does it well. I have tried to make another query: SELECT TOP 10 * FROM TABLE and always returns empty.
<%
String url,ssql;
int i,j,k;
int reg[]=new int[256];
try{
Class.forName("com.microsofto.sqlserver.jdbc.SQLServerDriver");
url="jdbc:sqlserver://localhost/;databaseName=acsc;user=user;password=1234";
Connection conn = DriverManager.getConnection(url);
Statement stc = conn.createStatement();
ssql="SELECT Nombre,max(Registro) FROM Tabla Group by Nombre order by Nombre";
ResultSet rsc= stc.executeQuery(ssql);
i=1;
while(rsc.next()){
reg[i]=rsc.getInt(2);
i++;
}
j=0;
do{
//ssql="SELECT * FROM Tabla Where Registro="+String.valueOf(reg[j]);
ssql="SELECT TOP 10 * FROM Tabla";
rsc= stc.executeQuery(ssql);
if(!(rsc.getRow()==0)){
out.println(rsc.getString(1)+" "+rsc.getString(2)+" "+rsc.getString(3));
}else{
out.println("vacio");
}
j++;
}while(j<i);
}catch(SQLException se){
out.println(se.toString());
}
%>
There are two problems with your code. The only one you need to fix is that you're not using Parameters in your SQL query. See
public static void executeStatement(Connection con) {
try(PreparedStatement pstmt = con.prepareStatement("SELECT LastName, FirstName FROM Person.Contact WHERE LastName = ?");) {
pstmt.setString(1, "Smith");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("LastName") + ", " + rs.getString("FirstName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
Using an SQL Statement with Parameters
Thank you for your response and sorry for not having responded before.
I have tried using prepareStatement, but the ResultSet kept returning empty.
I finally found where I had the problem, if!(Rsc.getRow()==0)) always returned 0, even if the ResulSet had records.
I have removed that part of the program and I have placed while rsc.next() and it works correctly.
What is the second problem that my code has?
Thanks greetings

JAVA - getTime() from DB - always getting 01:00:00

I have this code for selecting time from my database (SQLite):
String sql = "select cas from mytable where id = 'S222'";
Statement stmt2;
try {
stmt2 = con.createStatement();
ResultSet rs = stmt2.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
while (rs.next()) {
Time cas = rs.getTime("cas");
System.out.println(cas.toString());
}
} catch (SQLException ex) {
...
}
I am always getting value: 01:00:00 and in the database, there is a time set to 09:10:00
When I run this sql select statement in database by "execute command" I get right value. But when I run it from java application, it always prints 01:00:00. What is the problem? When I am selecting something else, not time, it is correct.
And I tried following select:
String sql = "select cas from mytable where id = 'S222' and cas = '09:10:00'";
And it also prints 01:00:00
I solved it!
instead of:
Time cas = rs.getTime("cas");
I used:
String cas = rs.getString("cas");
and it works. TY

JDBC returns an empty result set

ResultSet is empty although query should return whole table. Here is my code
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost","somonjon","sa");
con.setCatalog("ChatDBS");
Statement stmt = null;
String SQL = "SELECT * FROM Login_chat";
stmt = con.createStatement();
try{
System.out.println("trying execute query");
rs = stmt.executeQuery(SQL);
}
catch(SQLException ex){
ex.printStackTrace();
}
this is the error message:
trying execute query
com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no current row.
P.S.
Okey guys I'm not sure is it important or not, but this codes is jButton1ActionPerformed event.
AFAIK, you are not suppose to get this exception unless you are doing some operation over ResultSet like rs.next();
Regarding the problem is concerned, there could be two scenarios
You are not pointing to right database (catalog)
You have not committed the transaction in the database.
You have to loop through rs.
String column1;
int column2;
while (rs.next()) {
column1 = rs.getString("nameColumn1");
column2 = rs.getInt("nameColumn2");
}
Ok, in
String SQL = "SELECT * FROM Login_chat";
You have to add a ";".
String SQL = "SELECT * FROM Login_chat;";
Try with that!

Column is not indexed even though it is. PreparedStatement inside

I'm really struggling with a bug that did not appear on my dev environment, only once deployed in test.
I'm using a prepared Statement to run around 30 000 query in a row. The query check for the similarity of a string with what's in our database, using the oracle fuzzy method.
The column checked is indexed, but, don't know why, it fails randomly after some iterations, saying that index does not exists.
I don't understand what's going on, as the index really exists. My method never rebuild or delete the index so there is no reason for this error to appear ...
public List<EntryToCheck> checkEntriesOnSuspiciousElement(List<EntryToCheck> entries, int type,int score, int numresults, int percentage) throws Exception {
Connection connection = null;
PreparedStatement statementFirstName = null;
PreparedStatement statementLastname = null;
int finalScore = checkScore(score);
int finalNumResults = checkNumResults(numresults);
int finalPercentage = checkPercentage(percentage);
try {
connection = dataSource.getConnection();
StringBuilder requestLastNameOnly = new StringBuilder("SELECT SE.ELEMENT_ID, SE.LASTNAME||' '||SE.FIRSTNAME AS ELEMENT, SCORE(1) AS SCORE ");
requestLastNameOnly.append("FROM BL_SUSPICIOUS_ELEMENT SE ");
requestLastNameOnly.append("WHERE CONTAINS(SE.LASTNAME, 'fuzzy({' || ? || '},' || ? || ',' || ? || ', weight)', 1)>? ");
requestLastNameOnly.append((type > 0 ? "AND SE.ELEMENT_TYPE_ID = ? " : " "));
requestLastNameOnly.append("ORDER BY SCORE DESC");
statementLastname = connection.prepareStatement(requestLastNameOnly.toString());
for (EntryToCheck entryToCheck : entries) {
ResultSet rs;
boolean withFirstName = (entryToCheck.getEntryFirstname() != null && !entryToCheck.getEntryFirstname().equals(""));
statementLastname.setString(1, entryToCheck.getEntryLastname().replaceAll("'","''"));
statementLastname.setInt(2, finalScore);
statementLastname.setInt(3, finalNumResults);
statementLastname.setInt(4, finalPercentage);
if(type > 0){
statementLastname.setInt(5, type);
}
System.out.println("Query LastName : " + entryToCheck.getEntryLastname().replaceAll("'","''") );
rs = statementLastname.executeQuery();
while (rs.next()) {
Alert alert = new Alert();
alert.setEntryToCheck(entryToCheck);
alert.setAlertStatus(new AlertStatus(new Integer(AlertStatusId.NEW)));
alert.setAlertDate(new Date());
alert.setBlSuspiciousElement(new BlSuspiciousElement(new Integer(rs.getInt("ELEMENT_ID"))));
alert.setMatching(rs.getString("ELEMENT") + " (" + rs.getInt("SCORE") + "%)");
entryToCheck.addAlert(alert);
}
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
finally {
DAOUtils.closeConnection(connection, statementLastname);
}
return entries;
}
Really don't know what to look at ...
Thanks !
F
I never used Oracle text tables but my advice is:
Make sure that no one else is executing DDL statements on the table simultaneously.
Also, make sure that, index you have is context index.
Create an index for your column where you want to apply search
........................................
CREATE INDEX "MTU219"."SEARCHFILTER" ON "BL_SUSPICIOUS_ELEMENT " ("LASTNAME")
INDEXTYPE IS "CTXSYS"."CONTEXT" PARAMETERS ('storage CTXSYS.ST_MTED_NORMAL SYNC(ON COMMIT)');
..........................................