org.postgresql.util.PSQLException: ERROR: column "dsa" does not exist - postgresql

I am trying to develop a java web app. It is connected to a postgresql database. In this database, I have a table called emp99.In it there is a column called company. when I try to add values to the table I get an error which is:
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [insert into emp99(name,salary,designation,age,surname,department,company,address,working) values('s',1.0,'d',4,'ff',gg,'dd',true )]; nested exception is org.postgresql.util.PSQLException: ERROR: column "gg" does not exist
But I have this column
CREATE TABLE emp99 (
id int PRIMARY KEY,
name VARCHAR ( 50 ) ,
salary float ,
designation varchar(50),
age int,
surname varchar(50),
department varchar(50),
company varchar(50),
address varchar(50),
working Boolean
);
and this is my adding code:
public int save(Emp p){
String sql="insert into emp99(name,salary,designation,age,surname,department,company,address,working) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"',"+p.getAge()+",'"+p.getSurname()+"',"+p.getCompany()+",'"+p.getAddress()+"',"+p.getWorking()+" )";
return template.update(sql);
}

#stiky bit you were right i was missing Quotes. The correct one:
public int save(Employee p){
String sql="insert into emp89(name,salary,surname,departmentname,company,address,working,age,saat) values('"+p.getName()+"','"+p.getSalary()+"','"+p.getSurname()+"','"+p.getDepartmentname()+"','"+p.getCompany()+"','"+p.getAddress()+"','"+p.getWorking()+"','"+p.getAge()+"','"+saat+"')";
return template.update(sql);

Related

F# SqlProvider: System.Exception: Error - you cannot update an entity that does not have a primary key. (public.users)

I'm using the SQLProvider type-provider project: https://fsprojects.github.io/SQLProvider/
As the documentation states on CRUD usage, I'm trying to update a row like this:
let UpdateGpsLocation(gpsLocationDetails: UpdateGpsLocation) =
let ctx = SQL.GetDataContext()
let maybeFoundUser =
query {
for user in ctx.Public.Users do
where(user.UserId = gpsLocationDetails.UserId)
select(Some user)
exactlyOneOrDefault
}
match maybeFoundUser with
| Some user ->
user.GpsLatitude <- Some gpsLocationDetails.Latitude
user.GpsLongitude <- Some gpsLocationDetails.Longitude
ctx.SubmitUpdates()
| None -> failwithf "User %i not found" gpsLocationDetails.UserId
But it is failing with this:
System.Exception: Error - you cannot update an entity that does not have a primary key. (public.users)
at FSharp.Data.Sql.Providers.PostgresqlProvider.createUpdateCommand(IDbConnection con, StringBuilder sb, SqlEntity entity, FSharpList`1 changedColumns)
at <StartupCode$FSharp-Data-SqlProvider>.$Providers.Postgresql.FSharp-Data-Sql-Common-ISqlProvider-ProcessUpdates#1205-8.Invoke(SqlEntity e)
at Microsoft.FSharp.Collections.SeqModule.Iterate[T](FSharpFunc`2 action, IEnumerable`1 source) in D:\a\_work\1\s\src\fsharp\FSharp.Core\seq.fs:line 497
at FSharp.Data.Sql.Providers.PostgresqlProvider.FSharp-Data-Sql-Common-ISqlProvider-ProcessUpdates(IDbConnection con, ConcurrentDictionary`2 entities, TransactionOptions transactionOptions, FSharpOption`1 timeout)
at <StartupCode$FSharp-Data-SqlProvider>.$SqlRuntime.DataContext.FSharp-Data-Sql-Common-ISqlDataContext-SubmitPendingChanges#110.Invoke(Unit unitVar0)
at FSharp.Data.Sql.Runtime.SqlDataContext.FSharp-Data-Sql-Common-ISqlDataContext-SubmitPendingChanges()
at BackendDataLayer.Access.UpdateGpsLocation(UpdateGpsLocation gpsLocationDetails) in C:\Users\knocte\Documents\Code\RunIntoMeMASTER\src\BackendDataLayer\Access.fs:line 34
But the table has a primary key! In particular, it's using the SERIAL feature of PostgreSQL, this way:
CREATE TABLE users (
user_id SERIAL PRIMARY KEY
, gps_latitude FLOAT8
, gps_longitude FLOAT8
);
Is this a bug in SqlProvider project? Or maybe just in its PostgreSQL component?
I was able to reproduce this problem, there seems to be an issue with using user_id as the column name here.
This is just a workaround but changing the column name to "UserId" (double-quotes included!) fixed the issue for me.
See the new schema:
CREATE TABLE "Users" (
"UserId" SERIAL PRIMARY KEY
, "GpsLatitude" FLOAT8
, "GpsLongitude" FLOAT8
);
(If you don't use the double-quotes, it will convert UserId into Userid and your F# code won't compile.)

MIGRATION FAILED ENUM TYPE ALREADY EXISTS ERROR

I'm building a microservices app using Spring Boot + Postgres + Flyway,
within flight-archive microservice, I created a script sql that contains the following code:
CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method Payment_method,
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)
)
then, when I run flight-archive microservice using maven, I got the following error
SQL State : 42710
Error Code : 0
Message : ERROR: type "payment_method" already exists
Location : db/migration/V1__flight_archive_table.sql (C:\Users\OMAYMA\flight-app-
demo\server\flight-booking-
archive\target\classes\db\migration\V1__flight_archive_table.sql)
Line : 1
Statement : CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD')
In Postgres if you want to use uppercase you have to use quotation marks, otherwise, the words will always be in lowercase.
Try making this change:
CREATE TYPE "Payment_method" AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method "Payment_method",
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)

Include columns from related table in JPA using ListAll()

I have 2 related tables and i am wondering if it is possible to include other columns (like firstname and surname) from table no1 when i am calling the function ListAll() in table no2? I am using JPA with Session Beans (AbstractFacade) and JSF Pages. Thanks in advance :-)
Table No1
CREATE TABLE cases (
caseid INT AUTO_INCREMENT PRIMARY KEY,
category VARCHAR(32),
descript VARCHAR(512),
isDone TINYINT,
userid INT,
INDEX user_ind(userid),
FOREIGN KEY (userid) REFERENCES USERS(userid)
);
Table 2
CREATE TABLE users (
userid INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(64) NOT NULL,
surname VARCHAR(64) NOT NULL,
telephone VARCHAR(12),
email VARCHAR(64),
PRIMARY KEY (userid)
);
Entity Controller
#Named(value = "caseController")
#SessionScoped
public class CaseController implements Serializable {
#EJB
CasesFacade casesFacade;
#Inject
CasesBean casesBean;
public List<Cases> getAll() {
return casesFacade.findAll();
}
If i correct understand maybe the good idea will be unpack chosen columns/fields to custom DTO on level repository or in code.

retrieve numeric(10,2) data type from postgresql to Java.Math.BigDecimal in Java. SUM() function Postgresql

I have a numeric(10,2) data type column named "Value" in a Payment table in postgresql Database.
CREATE TABLE IF NOT EXISTS PAYMENT(
PAYMENT_ID BIGINT NOT NULL DEFAULT nextval('payment_seq') PRIMARY KEY,
DATE TIMESTAMP,
PLACE VARCHAR(255),
VALUE NUMERIC(10,2) NOT NULL,
UTILISATEUR_ID BIGINT REFERENCES UTILISATEUR
);
I want to retrieve that numeric value by a BigDecimal Data Type in Java. (dto)
import java.math.BigDecimal;
public interface UserSumByGroup {
public String getFullName();
public BigDecimal getSumOfValues();
}
For some reason all the times the return values for the dto is null when I execute in the controller..
...
List<UserSumByGroup> usersGroupSumPaymnt = userRepo.userGroupSumPaymt();
model.addAttribute("userGroupListSumPaymt", usersGroupSumPaymnt);
System.out.println("usersGroupSumPaymnt=> "+usersGroupSumPaymnt.get(0).getSumOfValues());
...
SQL Query:
SELECT usr.FULL_NAME as fullName, SUM(VALUE) as paymentCount
FROM PAYMENT pym left join UTILISATEUR usr ON usr.utilisateur_id = pym.utilisateur_id
WHERE MONTH(pym.date) = MONTH(CURRENT_DATE)
AND YEAR(pym.date) = YEAR(CURRENT_DATE)
AND pym.utilisateur_id IN (1,5)
GROUP BY pym.utilisateur_id, usr.FULL_NAME;
Console Log:
usersGroupSumPaymnt=> null
Do you have some idea why I got always a Null?.
Thanks.
To correspond the names of the variables between Spring JPA and the Database, the names of the attributes of the dto object must be the same to the name of the result field in the query.
The name of the result query "paymentCount" needs to be the same as the dto instance "sumOfValues".
So, Change:
SUM(VALUE) as paymentCount
By
SUM(VALUE) as sumOfValues

What 's the best practice of change encrypted column's property

My [User] table which is having column [Email] encrypted using Always-Encrypt.
I need to limit [Email]'s length from max to MaxLength(250), I do this by add MaxLength(250) on the email property.
public class User
{
[Key, Required]
public Guid Id { get; set; }
[Required, **MaxLength(250)**]
public string Email { get; set; }
...
}
but when I run migration scripts, I got following exception:
Operand type clash: nvarchar(max) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK1', column_encryption_key_database_name = 'Identity') is incompatible with nvarchar
and the migration scripts is:
DECLARE #var0 nvarchar(128)
SELECT #var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.User')
AND col_name(parent_object_id, parent_column_id) = 'Email';
IF #var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[User] DROP CONSTRAINT [' + #var0 + ']')
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201804250659054_12345678', N'Concordya.PWC.Verify.DataAccess.Migrations.Configuration', 0x1F8... , N'6.2.0-61023')
I manually run the scripts in DB, same error.
Does that mean once the column is encrypted, the only way to change property is decrypt, modify, then encrypt?
Thanks,
Cheng
I came across a similar error when trying to increase the size of an Always Encrypted NVARCHAR column. The problem was that the ALTER COLUMN statement still needs to include the encryption parameters. So for example you could alter this -
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
To this (or whatever you originally set the Always Encrypted parameters to) -
ALTER TABLE [dbo].[User] ALTER COLUMN [Email] [nvarchar](250) NOT NULL
ENCRYPTED WITH (
ENCRYPTION_TYPE = DETERMINISTIC
, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256'
, COLUMN_ENCRYPTION_KEY = [**YOUR KEY**]
) NULL