how to update a record in mysql through java - java

I am currently trying to code a java program for a school project that has a mysql database of sportsclub members. I want to use the id of the members in order to change the number of classes that someone skipped. However my Java code always fails to run and outputs the exception message. My database is called demo1 and the field im trying to update is Consecutiveskips. The id field is called (id)

Simplest way to update record is through statement
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection oCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String query="Update Demo1 SET Consecutiveskips=? where id=?";
PreparedStatement preparedStatement = oCon.prepareStatement(query);
preparedStatement.setInt(1, 233);
preparedStatement.setInt(2, 4);
In your code you are using setInt(6,1) but there is no 6th index present.
You should use
preparestaement.setInt(1,"yourconsicutiveskipvalue");
preparestaement.setInt(2,"idvalue");
Moreover, make sure to have mysql-connector.jar in classpath

Related

getGeneratedKeys() returns an Empty ResultSet

Hello there and thanks for reading.
I'm trying to retrieve the ID of the newly inserted data, but I always get an empty ResultSet.
Connection con = main.getCon();
String sqlCommand = "Insert Into Relations(name,explanation) values(?,?)";
PreparedStatement state =
con.prepareStatement(sqlCommand,Statement.RETURN_GENERATED_KEYS);
state.setString(1,name.getText());
state.setString(2,explanation.getText());
int affectedRows = state.executeUpdate();
assert (affectedRows>0);
ResultSet rs = state.getGeneratedKeys();
assert rs.next();
int instertedID= rs.getInt("ID");
Not sure what's wrong with it. Checked different samples online, but couldn't figure out what's my mistake.
I also tried it with Statement, but no luck with that either.
Point 1: the code runs smoothly and my data in inserted into the database.
Point 2: there are examples online for this very case, you can check it here:
https://www.baeldung.com/jdbc-returning-generated-keys
I just realized that my ResultSet wasn't empty, I had problem with using my debugger and that's why I thought it was empty.
As Mark Rotteveel mentioned in a comment, the problem was with "assert" statement.
The problem is your use of assert rs.next(). Assertions in Java are intended for checking invariants (eg during testing), but when you normally run Java, assert statements are not executed, they are only executed when explicitly enabling this with the -ea commandline option.
As a result, rs.next() is not called, so your result set is still positioned before the first row when you call rs.getInt(1). Instead use if (rs.next()) { ... }.
This is DB engine dependent. Some tips:
JDBC is low-level and not appropriate to program with
It's a complicated API. Use something that makes it easier: JDBI, or JOOQ. They may have abstractions over insertion that takes care of this stuff for you.
Some DB engines require that you list the column name
Try:
con.prepareStatement(sqlCommand, new String[] {"UNID"});
Some DB engines will only return generated values as direct resultset
Don't call .executeUpdate(); instead, call .executeQuery() which returns a ResultSet; check that one.
Something else
Post the exact table structure and DB engine you're working with if the above doesn't help.
Your code is broken
You can't create resource objects (once that must be closed) unless you do so safely, and you're not doing so safely. Use try-with-resources:
String sql = "INSERT INTO relations(name, explanation) VALUES (?, ?)";
try (Connection con = main.getCon();
PreparedStatement ps = con.prepareStatement(sql, new String[] {"unid"})) {
state.setString(1, name.getText());
state.setString(2, explanation.getText());
try (ResultSet rs = state.executeQuery()) {
if (!rs.next()) throw new SQLException("insert didn't return autogen?");
System.out.println(rs.getInt(1));
}
}
ResultSets, Statements, PreparedStatements, and Connections are all resources (must be closed!) - if you want to store one of those things in a field, you can do that, but only if the class that contains this field is itself a resource: It must have a close() method, it must implement AutoClosable, and you can then only make instances of this class with try-with-resources as above.
Failure to adhere to these rules means your app seems to work, but is leaking resources as it runs, thus, if you let it run long enough, it will start crashing. Also, your DB engine will grind to a halt as more and more connections are left open, stuck forever.
change the last line of code to this because the DBMS you are using may not support the getting value by column name so pass the index of that column:
int instertedID = rs.getInt(1);
String sqlCommand = "Insert Into Relations (name, explanation) values(?, ?)";
PreparedStatement state = con.prepareStatement(sqlCommand, Statement.RETURN_GENERATED_KEYS);
state.setString(1,name.getText());
state.setString(2,explanation.getText());
state.executeUpdate();
ResultSet resultSet = state.getGeneratedKeys();
if(resultSet.next()) {
System.out.println(resultSet.getInt(1)); //Indicate the corresponding column index value.
}

How to get the full query that a PreparedStatement is about to execute in DB2?

I'm working on a dynamic web project and using the PreparedStatement to execute the SQL queries against the DB2 database.
String myQuery = "select id from user where name = ?";
PreparedStatement stmt = connection.prepareStatement(myQuery);
stmt.setString(1, test);
ResultSet resultSet = statement.executeQuery();
How can I receive the full SQL query that is about to be executed on the DB2 server in the console?
If you are familiar with Debugging options in Eclipse. You may try the following:
Set a Breakpoint at ResultSet resultSet = statement.executeQuery();
Right click your application, say Debug As select Java Application (or Whatever applicable in your case i.e. may be SpringBoot App etc.
Perform step that gets you to code mentioned in the Question.
If you check Variables tab in Debug Perspective of Eclipse, you will find variables like myQuery , stmt (according to your code)
Whatever you see as value of stmt would be the full SQL query you need.
Also, if you don't want to keep looking at this variable always you may try Java Logging and Print your Full SQL query in Logs.

Java HSQLDB connection issue

I have been making a program that is using HSQL to connect to a database that I created. For some reason some methods in my class can call on the database and perform commands, while other parts cannot. I keep getting this error,
java.sql.SQLFeatureNotSupportedException: feature not supported
and here is the method,
public List<CustomerInfo> DBgetInfo(String Customer)
throws ClassNotFoundException, SQLException {
Class.forName("org.hsqldb.jdbcDriver");
Connection con = DriverManager.getConnection(urlConnection, userId,
password);
Statement stmt= con.createStatement();
String query = "SELECT * FROM PUBLIC.CUSTOMER";
ResultSet rs = stmt.executeQuery(query);
rs.first(); //The error happens on this line
rs.close();
stmt.close();
con.close();
}
I have ran the debugger multiple times and there error is in this method on the rs.first line. I have tried remaking the DB, reimporting all the files, checking to make sure the command is correct, and ect... The weird thing is that earlier in this class I have a method very similar to this, but it has no issues. I really can't figure out what the problem is.
According to the documentation this error occurs:
Throws:
SQLException - if a database access error occurs, this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Earlier on the same page, there is a section on HSQL specific details for result sets. To call first you need to modify your statement creation:
ResultSet object generated by HSQLDB is by default of ResultSet.TYPE_FORWARD_ONLY (as is standard JDBC behavior) and does not allow the use of absolute and relative positioning methods. If a statement is created with:
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
then the ResultSet objects it produces support using all of the absolute and relative positioning methods of JDBC2 to set the position of the current row...
But you might want to think about why you need to call first.

Trying to run alter session command to set session variable through JDBC

I am trying to run an alter system command through JDBC which is required for me to run a query optimally.
I`m not sure if I am doing it right as I am not able to see the effect of the alter session statement. How do we persist the same session in JDBC what I mean is if I use the same connection and not close it does it mean I am using the same session?
The connection and database class are just helper classes to get a connection.
MyConnection mainDatabaseConnection = new MyConnection("jdbc:oracle:thin:#aas:111:"+tm.databaseName, "sys as sysdba", "xxx");
Database mainDatabase = new Database(mainDatabaseConnection.getConnection());
/* Fill in with data got for the main database */
//String auditQuery = mainDatabase.generateAuditQuery(tm.schemaName, tm.tableName);
String auditQuery = "select id, name, school, start, end from user where start>'11-11-11' and start<'12-12-12'";
System.out.println(auditQuery);
ResultSet rs = mainDatabase.runQuery("ALTER SESSION set optimizer_use_invisible_indexes = true");
// ResultSetMetaData md = rs.getMetaData();
// System.out.println(md.getColumnCount());
rs.close();
mainDatabase.close();
mainDatabaseConnection.close();
I am not sure if the alter session command ran successfully.
Question 2: When I run a Select query using Statement I get a resultSet. WHen I close the statement does the resultSet get closed too? So, as soon as I close the statment or connection does all the fetched data go away?
A java.sql.Connection object represents a session in Oracle. As long as you keep using the same object, you're in the same session.
With regard to closing Statements, as Mark Rotteveel commented - closing a Statement will indeed close a ResultSet that was opened by it. It would, however, be recommended to close the RestulSet once you're done with it, even (or, actually - especially) if you intend to reuse the Statement object.

ORA-00942: table or view does not exist error on writing to a table in database

I am trying to read a data from one database table using java + jdbc and trying to insert into another database table on different server in same session.
I have created 2 connection object(con,conn1), each pointing to correct database.
With 1st con object i am able to read the data but When it is going to write the data to another table using conn1 it is failing with error
ORA-00942- table or view doesnt exist.
I have also cross-checked that table is present and we can write to that table.
with a standalone class and static data i was able to write to that table.
Please let me know what is wrong in my approach.
Code sample:
public static void main
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection( "URL","uname","passwd");
//code to read from db and add to arraylist.
close resultset, con.
This connection obj points to new a database and url
Connection con1 = DriverManager.getConnection( "url","uname","passwd");
PreparedStatement pstmt = con1.prepareStatement("insert into SCHEMA_NAME.TABLE_NAME(columns) values(?,?,?,?,?,?,?,?)");
//code to iterate the arraylist populated above
pstmt.setint etc
pstmt.executeUpdate();
It fails after executeUpdate statement.
Yes, problem was with pstmt.setClob field. I changed it to pstmt.setString and took .toString() of clob object and it worked.
I m still puzzled why it throws table or view doesnt exist error.

Categories

Resources