JDBC not updating sqlite table at specific column - java

I've encountered this very strange behaviour, where I construct a string to update a row of a table such as the following:
sql = "UPDATE cosmetics SET trail = 4,color = '[blue]',doTrail = 0,trails = null,trailSeen = null,inventory = null,uuid = 'abcd' WHERE uuid = 'abcd'";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
pstmt.close();
In a try catch, and the code runs fine.
My issue is everything but the first column mentioned(ie, trail in this case) is updated. If I check the table from sqlite with:
SELECT * FROM cosmetics WHERE uuid = 'abcd';
It returns
uuid|trail|doTrail|color|inventory|trails|trailSeen
abcd|0|0|[blue]|||
where previously, the value was:
uuid|trail|doTrail|color|inventory|trails|trailSeen
abcd|0|1|[white]|||
So doTrail was updated, and so was color, the only thing not updated was trail. I have no idea why this is, so any help would be much appreciated.
Here's the .schema cosmetics
CREATE TABLE cosmetics (uuid TEXT PRIMARY KEY, trail INTEGER, doTrail BOOLEAN, color TEXT DEFAULT "[white]", inventory TEXT, trails TEXT, trailSeen TEXT);
I should also mention if I copy and paste the value of sql directly into a terminal, there are no issues and the table is updated as expected.

Related

Java & SQL - Can't create duplicate values in my primary and foreign key

Go easy on me, middle school teacher taking a CS class. I've got a Java program that asks for user name, height, weight, does some calculations and gives results to the user. I now need to store this data in a database. I can get the data to store until I start using primary and foreign keys.
Here is the error I can't figure out:
Error: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL180429151131780' defined on 'USERPROFILE'.
Here is my table:
drop table stayfitapp.userdata;
drop table stayfitapp.userprofile;
drop schema stayfitapp restrict;
create schema stayfitapp;
create table stayfitapp.userprofile
(
profileName varchar(255) not null primary key,
profileGender varchar(255) not null
);
create table stayfitapp.userdata
(
profileAge double not null,
profileWeight double not null,
profileHeight double not null,
profileWaistCircumference double not null,
profileHipCircumference double not null,
profileName varchar(255),
foreign key (profileName) references stayfitapp.userprofile(profileName)
);
Here is the section of the "app" that writes to the table...
public void save(){
try {
String query = "insert into stayfitapp.userprofile" + "(profileName, profileGender)" + "values" + "(?,?)";
String query2 = "insert into stayfitapp.userdata" + "(profileAge, profileWeight, profileHeight, profileWaistCircumference, profileHipCircumference)" + "values" + "(?,?,?,?,?)";
Connection myConnection = DriverManager.getConnection("jdbc:derby://localhost:1527/stayfitDB2", "username", "password");
Statement myStatement = myConnection.createStatement();
//Statement myStatement2 = myConnection.createStatement();
PreparedStatement prepared = myConnection.prepareStatement(query);
prepared.setString(1, profileName);
prepared.setString(2, profileGender);
PreparedStatement prepared2 = myConnection.prepareStatement(query2);
prepared2.setDouble(1, profileAge);
prepared2.setDouble(2, profileWeight);
prepared2.setDouble(3, profileHeight);
prepared2.setDouble(4, profileWaistCircumference);
prepared2.setDouble(5, profileHipCircumference);
int rowsAffected = prepared.executeUpdate();
int rowsAffected2 = prepared2.executeUpdate();
if(rowsAffected==0)
{
System.out.println("Warning: User data did not save!");
}
else
{
System.out.println("User info saved!");
}
}
catch(SQLException e)
{
System.out.println("Error: "+e.toString());
}
Your save() method will attempt to add the user to the stayfitapp.userprofile table. This table has a field called profileName. profileName is the "primary key" so no duplicate values are allowed.
The error that you are getting is saying that you cannot add(insert) the record to the table because the table already has a record with the same name.
Does your program work okay if you use a different name each time?
You will need to add some logic to your program to deal with the scenario where the profileName already exists in the table. This will probably involve deleting or updating the existing record.
This is the problem.
insert into stayfitapp.userprofile"
+ "(profileName, profileGender)" + "values" , etc
You have nothing to check to see if a record already exists. Something like this would work better.
insert into stayfitapp.userprofile
profileName, profileGender
select distinct ?, ?
from someSmallTable
where not exists (
select 1
from stayfitapp.userprofile
where profileName = ?
)
The someSmallTable bit depends on your database engine, which you didn't specify.
I ended up writing a method to check if the username was already in the profile table. If the username was a duplicate I only wrote to the data table. If the username was new I wrote to both tables.
Thank you for your help! I'm sure there was a more efficient method (figuratively and literally) but I'm on to my final project and nearly surviving an actual CS class.

DatabaseMetaData.getColumns returns columns of similar named tables

In my database I have tables "EMPLOYEE_DETAILS" and "EMPLOYEE DETAILS" with different columns for both tables. When I used the getColumns() method of the DatabaseMetaData (java.sql.DatabaseMetaData) to get the column details of the table "EMPLOYEE_DETAILS", I am getting the columns of both "EMPLOYEE_DETAILS" and "EMPLOYEE DETAILS".
I have tried this for databases Oracle, MySql and MSSQL. The result is same.
The code which I have used to call the getColumns method is given below :
String tableName = "EMPLOYEE_DETAILS";
ResultSet columnResultSet = databaseMetaData.getColumns(null, null,tableName, null);
while (columnResultSet.next()) {
System.out.println(columnResultSet.getString("COLUMN_NAME"));
System.out.println(columnType = columnResultSet.getString("TYPE_NAME"));
System.out.println(columnSize = columnResultSet.getInt("COLUMN_SIZE"));
}
Could anyone please help me to resolve this.

SQL Update field without unique index fields

I have table without unique index tuples, lets say table has records
A->B->Status
A->C->Status
A->B->Status
A->B->Status
A->C->Status
I am getting first and second record, processing them. After then I want to update only these two records
how can I make this process possible at java application layer?
Since there is not any unique index tupples I cannot use update SQL with proper WHERE clause
Using
Spring 3.XX
Oracle 11g
I think you may try to use ROWID pseudocolumn.
For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row:
The data object number of the object
The data block in the datafile in which the row resides
The position of the row in the data block (first row is 0)
The datafile in which the row resides (first file is 1). The file
number is relative to the tablespace.
Usually, a rowid value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same rowid.
SELECT ROWID, last_name
FROM employees
WHERE department_id = 20;
The rowid for the row stays the same, even when the row migrates.
You can solve this issue by using updatable resultsets. This feature relies on rowid to perform all modifications (delete/update/insert).
This is a excerpt highlighting the feature itself:
String sqlString = "SELECT EmployeeID, Name, Office " +
" FROM employees WHERE EmployeeID=1001";
try {
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sqlString);
//Check the result set is an updatable result set
int concurrency = rs.getConcurrency();
if (concurrency == ResultSet.CONCUR_UPDATABLE) {
rs.first();
rs.updateString("Office", "HQ222");
rs.updateRow();
} else {
System.out.println("ResultSet is not an updatable result set.");
}
rs.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Here is a complete example.

PostgreSQL: Update my user table via Java

In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";

Selecting a record from a mysql db

I am trying to select data from my db, but instead of getting a certain field I get "".
My table name is locations and it's look like this:
id - int,
location - varchar and time - timestamp.
I would like to select the last location based on the time, here is my code:
this.select = this.conn.createStatement();
ResultSet result = select.executeQuery("SELECT location FROM locations ORDER BY time DESC Limit 1");
result.next();
System.out.println(result.getString(1));
I remind you the output is "";
To identify the column in your resultSet you can use:
result.getString("location");
did u try ?
System.out.println(result.getString(0));

Categories

Resources