Postgres Sql : Alter table - java

I am fetching all the records from the Excel sheet and adding columns into the database according to the Excel header row. After fetching I alter the table and adding columns into the newly created table and it works perfectly fine. but when I add one more column into the excel file and running the query again it supposed to add the column which I have created in the excel file but instead, it gives me an error of Column already exists
The query which I m running is
"ALTER TABLE " + name + " ADD " + cellValue + " varchar(5000)"
Thanks in advance..

If you want to create only columns that don't exist write your query like this
"ALTER TABLE " + name + " ADD if not exists " + cellValue + " varchar(5000)"

Related

UCanAccessSQLException: constraint violation

I'm having problems with my Java program.
I'm using MS Access as a database and UCanAccess to connect to the database.
When I'm trying to insert a text into the database, I get an Exception:
net.ucanaccess.jdbc.UcanaccessSQLException: integrity constraint violation: unique constraint or index violation; ENTRIES_PRIMARYKEY table: ENTRIES
This is the SQL statement, that results in the exception:
"INSERT INTO Entries (Text, Title, Date, Time) VALUES"
+ "(\"" + text + "\", \"" + title + "\", \"" + date + "\", \"" + time + "\");";
The primary keys of table Entries is (Title, Date).
The information I'm inserting does not exist in the table.
I've made a System.out.println() containing the same string to make sure the variables contain the correct information, and they do.
Can someone tell me what I'm doing wrong?
(from comment to question:)
I tried inserting a row, and it worked. But when I tried to insert more rows, the problem occurred.
If the Primary Key for the table is (Title, Date) then the values in those two columns (fields) must be unique across all rows. That is, you can insert a row that looks like
Text Title Date Time
---------- ------ ---------- --------
some text Title1 2015-06-01 05:56:15
but if you try to insert another row like this
Text Title Date Time
---------- ------ ---------- --------
other text Title1 2015-06-01 06:15:44
the insert will fail because that combination of Title and Date already exists in the table. Yes, that row "doesn't exist" because the Text and Time values are different, but the Primary Key constraint doesn't care; it only looks at the Title and Date columns.
If you really need to insert that second row then you'll need to change the Primary Key for the table.

UcanaccessSQLException: unexpected token: ORDER

I'm making a little app in Java and MySQL with PHPMyAdmin and all runs fine, but my professor says that we have to work with a database in Access, so I just changed my class connection and imported my database. The INSERT, SELECT and other UPDATE statements run fine but this statement just doesn't run.
UPDATE table SET col1=?, col2=? WHERE col0=? ORDER BY col4 DESC LIMIT 1
I can't understand how in MySQL it runs fine but with UCanAccess it doesn't work.
I can't understand how in MySQL it runs fine but with UCanAccess it doesn't work.
That's because the various producers of database software have taken it upon themselves to implement the SQL language in slightly different ways, so a given SQL statement written for MySQL is not guaranteed to work under Access, or Microsoft SQL Server, or Oracle, or any other "dialect" of SQL.
UCanAccess tries very hard to follow the Access SQL syntax. Access SQL uses TOP n instead of LIMIT n, but Access SQL also does not allow TOP n or ORDER BY in the main part of an UPDATE query. So you need to use a subquery to identify the primary key value of the row you want to update.
For example, if your table has a primary key column named "id" then you can do
sql =
"UPDATE table1 SET col1=?, col2=? " +
"WHERE id IN ( " +
"SELECT TOP 1 id " +
"FROM table1 " +
"WHERE col0=? " +
"ORDER BY col4 DESC, id " +
")";

Error executing Create table statement in Java?

I am trying to create 2 tables in MySql using Java JDBC,the first one runs fine but I get an error when I execute the second create table command. The problem looks like in the Foreign key definition not sure what's missing ?
Error :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near 'FOREIGN KEY(UniqueBusID)
REFERENCES BUS_3_CLEARBROOK_UFV_GOLINE_TO_UFV_BusDetai' at line 1
Code
String table_UniqueBusNameTimings = BusDetails+"_BusTimings";
String timings= "Timings";
String dayofweek = "DayOfWeek";
String FuniqueBusID = "UniqueBusID";
String table_UniqueBusNameDetails = BusDetails+"_BusDetails";
String PuniqueBusID = "UniqueBusID";
String StopNames = "StopNames" ;
String sql1 = "CREATE TABLE "+table_UniqueBusNameDetails+
"(UniqueBusID VARCHAR(255) not NULL, " +
" StopNames VARCHAR(1000), " +
" PRIMARY KEY ( UniqueBusID ))";
String sql2 = "CREATE TABLE "+table_UniqueBusNameTimings+
"(Timings VARCHAR(255) , " +
" DayOfWeek VARCHAR(25), " +
" UniqueBusID VARCHAR(255) "+
" FOREIGN KEY(UniqueBusID) REFERENCES "+table_UniqueBusNameDetails+"(UniqueBusID))";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
You have a comma missing after UniqueBusID VARCHAR(255). Just change it to UniqueBusID VARCHAR(255), and your code shall be fine.
For details on syntax related to CREATE TABLE with FOREIGN KEY, you can explore this page: http://www.w3schools.com/sql/sql_foreignkey.asp
We should use CREATE TABLE IF NOT EXISTS... then if we are having foreign key relation then we should use SET FOREIGN_KEY_CHECKS=0; Finally we will execute a batch what having all the statement and then commit.
Every attribute like column, index, foreign key etc. should be seprated by comma ',' in table creation syntax. so here a comma missing after UniqueBusID VARCHAR(255). It will be fine after adding comma here.
#Suzon: We should not set foreign_key_checks=0 specially during creating table or adding any constraint at it will skip any constraint checking by mysql and create major issue in database. We can use it only we are sure its impact for example we want to delete some rows from master table even child table contains corresponding rows and we are fine with this etc.

Insert into column family using Datastax java driver?

If I have a column family created like this in Cassandra as previously I was using Thrift based client..
create column family USER
with comparator = 'UTF8Type'
and key_validation_class = 'UTF8Type'
and default_validation_class = 'BytesType'
Then can I insert into above column family by using the Datastax Java driver with asynchonous / batch writes capability?
I will be using INSERT statement to insert into above column family? Is that possible using Datastax Java driver?
I am in the impression that I can only insert into CQL based tables using Datastax Java driver not in the column family design tables...
TL;DR
Sort of, but it is better to create a cql3 based table and continue from there.
First off to get a clear impression of what's going on use the describe command in cqlsh:
cqlsh> describe COLUMNFAMILY "USER";
CREATE TABLE "USER" (
key text,
column1 text,
value blob,
PRIMARY KEY (key, column1)
) WITH COMPACT STORAGE AND
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.000000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.100000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='NONE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
Then you can build insert statements using cqlh (i used cqlsh):
cqlsh:test> insert into test."USER" (key, column1, value) VALUES ('epickey', 'epic column 1 text', null);
If you do a select however...
cqlsh:test> SELECT * FROM test."USER" ;
(0 rows)
Once you've done that go back to the CLI:
[default#unknown] use test;
Authenticated to keyspace: test
[default#test] list USER;
Using default limit of 100
Using default cell limit of 100
-------------------
RowKey: epickey
1 Row Returned.
Elapsed time: 260 msec(s).
The last tool I'll use is sstable2json (takes all your data from an sstable and ... turns it into a json representation)
For the above single insert of the USER cf i got this back:
[
{"key": "657069636b6579","columns": [["epic column 1 text","5257c34b",1381483339315000,"d"]]}
]
So the data is there, but you just dont really have access to it over cql.
Note This is all done using C* 2.0 and cqlsh 4.0 (cql3)
Yes, using below code:
String query = "INSERT INTO " + keyspace_name + "." + column_family + " (" + column_names + ") VALUES (" + column_values + ");";
statement = session.prepare(query);
boundStatement = new BoundStatement(statement);
boundStatement.setString(0, key);
boundStatement.setString(1, subColNames[k]);
boundStatement.setMap(2, colValues);
session.execute(boundStatement);

Error in SQL statement for Derby database

I'm havin an error while trying to execute this piece of sql code... The error I'm getting is:
Encountered "(" at line 1, column 45
The piece of code is:
ALTER TABLE APP.RESPOSTAS ADD coluna" + (numColumns + 1) + " INTEGER(1) AFTER coluna" + numColumns;
Can anyone help me?
Thank you all!
According to The derby details for INTEGER you don't need the (1) in there.
ALTER TABLE APP.RESPOSTAS ADD coluna" + (numColumns + 1) + " INTEGER
should work?
edited to remove the AFTER section as it doesn't look like derby supports that either.
here are the derby details for ALTER TABLE

Categories