This question already has an answer here:
Problem with adding rows with JDBC and MySQL?
(1 answer)
Closed 4 years ago.
I am having a problem with updating a result set given by mssql.
I want to update a column (initial_deposit) in the table (createaccount with a primary key id) with a new value that is found after adding (initial and the AmountDeposited). AmountDeposited is entered as a double on a textField named (textFieldamount) and initial is also a double value from the result set.
I am getting an error. (Result Set not updatable (referenced table has no primary keys).
This result set must come from a statement that was created with a result set type of ResultSet.CONCUR_UPDATABLE.)
Here is my code
String url = "jdbc:mysql://localhost:3306/STATTER_BANK";
String user = "root";
String password = "";
double amountDeposited = Double.parseDouble(textFieldamount.getText());
public void theQuery {
String query1 = "SELECT initial_deposit FROM createaccount"+"WHERE id=1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement stt = con.prepareStatement(query1, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stt.executeQuery();
while (rs.next()) {
double initial = rs.getDouble("initial_deposit");
rs.updateDouble( "initial_deposit", initial + amountDeposited);
rs.updateRow();
}
} catch (Exception e ) {
e.printStackTrace();
}
}
You can refer.
similar question perhaps it is the same one
Changing ResultSet.TYPE_SCROLL_SENSITIVE with ResultSet.TYPE_SCROLL_INSENSITIVE should work.
Related
I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}
This question already has answers here:
Using Prepared Statements to set Table Name
(8 answers)
Closed 6 years ago.
this is my current java program. I need to make a prepared statement and connect to a MySql database.
try {
Connection connect = DriverManager.getConnection(host, username, password);
System.out.println("works fine connected");
/*
*
* */
String Dquery = ("SELECT * FROM ?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book");
System.out.println("mySql statemnt: "+Dquery);
//execute the query, and get a java resultset
ResultSet rs = st.executeQuery();
//iterate through the java resultset
while (rs.next())
{
String id = rs.getString(Column1);
String firstName = rs.getString(Column2);/*
String lastName = rs.getString(Column3);
String dateCreated = rs.getString(Column4);
int isAdmin = rs.getInt (Column5);*/
//print the results
System.out.println(id+"|\t"+firstName/*+"|\t\t"+lastName+"|\t\t"+dateCreated+"|\t"+isAdmin*/);
}
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I cant insert the "lmgs_Book" String into the prepared statement.
Prepared statement is for the column values not for table name.
But you can use placeholder in place of table name and then replacing
that with your tablename.
String Dquery = ("SELECT * FROM $tableName");
Dquery = Dquery.replace("$tableName","lmgs_Book");
PreparedStatement st = connect.prepareStatement(Dquery);
Remove this:
st.setString(1, "lmgs_Book");
Caution:
And what is the advantage compared to
String Dquery = "SELECT * FROM lmgs_Book";? [Recommended]
Answer: No advantage at all. You may embrace potential harms if you use placeholder in table name like above.
(especially since you should not use a variable in the replace call
instead of the literal, since that might make the statement vulnerable
to SQL injection)
try this and Please make sure your queryString column Name must be a varchar in your database.
String Dquery = ("SELECT * FROM tablename where column_name =?");
//create the java statement
PreparedStatement st = connect.prepareStatement(Dquery);
st.setString(1, "lmgs_Book"); //this line will be set Imgs Books as search Parameter.
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 7 years ago.
I want to get the last inserted ID as long. Because the primary key of my table is of long data type.
Here's my code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
System.out.println("LAST INSERTED ID = "+lastInsertedID);
} catch (Exception e) {
e.printStackTrace();
}
I've tested that when the maximum value of integer reaches I get last 1 as last inserted_id.
By the way, I've gone through this post.
Thanks.
try with the following code snippet:
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
Here's the full code:
Connection connection = null;
Statement statement = null;
try {
String sql = "INSERT INTO testTable(name) VALUES('Anonym')";
connection = DriverManager.getConnection(DB_URL, USER, PASS);
statement = connection.createStatement();
long lastInsertedID = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs= statement.getGeneratedKeys();
if (rs.next())
{
System.out.println("Last Inserted ID = "+rs.getLong(1));
}
} catch (Exception e) {
e.printStackTrace();
}
This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 8 years ago.
I've spent hours looking at what seems like what should be perfectly working code. The connection.createStatement() version of this method works fine but as soon as I try to convert it over to the better, connection.prepareStatement() version it throws a MySQLSyntaxErrorException and complains about a problem near the '?' character in my query string. The code is posted below and I simply cannot see the problem with it. The database field is VARCHAR and accepts Strings so that is not the problem.
public Discussion getDbDiscussionInstance(String _instanceId) throws SQLException {
String qryStr = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
// Try to build the object with existing data.
try {
qryStr = "SELECT assignment_id, discussion_id, section_id, user_id, circle_id, breakout_id, title, description, created, due FROM macb_discussions WHERE instance_id=?";
myStmt = connection.prepareStatement(qryStr);
myStmt.setString(1, _instanceId);
myRs = myStmt.executeQuery(qryStr);
if (rs.next()) {
this.discussionId = myRs.getString("discussion_id");
}
} catch (SQLException e) {
dbFunc.catchSQLException(e);
} finally {
myRs.close();
myStmt.close();
}
}
Use only myStmt.executeQuery(); without the argument, you have already preperad the statement
From the docs,
Statement.executeQuery(String sql)
PreparedStatement.executeQuery()
So change your function accordingly.
myStmt = connection.prepareStatement(qryStr); to
myStmt = connection.prepareStatement();
EDIT: I had a letter off, it's working now.
I have the following sql statement
UPDATE names set sent_count = sent_count + 1 where user_name = 'name' AND category = 'test' AND service = 'test'
this works by increasing the sent_count each time I run the sql from PGAdmin3, but I have the following method in a Java program using Postgresql JDBC, it's not throwing any exceptions but it's not increasing sent_count here is the method below
public void increaseUsernameResponseCount(String userName, String category, String service, String country) throws SQLException
{
Connection conn = null;
PreparedStatement pst = null;
// ResultSet rs = null;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("UPDATE names set sent_count = sent_count + 1 where user_name = ? AND category = ? AND service = ?");
pst.setString(1, userName);
pst.setString(2, category);
pst.setString(3, service);
int count = pst.executeUpdate();
System.out.println(count);
}
catch (Exception e)
{
System.out.println(e);
}
finally
{
pst.close();
conn.close();
}
}
the count counter prints 0 when this method is ran. Any idea why it does not work from the method but it works when I execute the sql query?
Check if you have two databases containing the same table. This generally happens if you work at two different locations and keep changing database names while importing it from the dump.
Also check if the "url" and "props" strings are correct for the database.