Delete old table and create new one and prepopulate it - RoomDatabase - java

I am creating a simple android application in android studio with java.
I have a roomdatabase db with a table named user that has four columns
name, profession, age, description and I have prepopulated using a database that i made in sqlite studio.
Now, I want to add a column surname on the table but I want to delete all the prepopulated data and prepopulate again the table with a new database that contains also surname.
At first I thought to use auto migrations and to just add a new column. But i don't know how delete all the existing data and prepopulate again the database.
I want to delete the existing data because i want to change all the info that exists in the column description. Also as concern as the column name now it contains the fullname and in some cases is written line "name surname" and other times like "surname name" e.x "Will Smith" "Smith Will". Now I want to have the name and the surname in separate columns name and surname
Could someone recommend me something? Thank you in advance

AutoMigration will not cope with amending the data itself. Thus you will have to do that manually and thus use a destructive migration.
Here's a example (as can be seen actually undertaken)
Note this assumes no version or version 1 was assigned to the original pre-populated database and also that 1 was used for the version passed to the #Database annotation.
an SQLite database has, as part of it's header, a user_version number (offset 60 for 4 bytes). It is comparing this to the version passed to Room that determines the migration/auto migration. As is seen changing this is critical if migrating.
If developing you could just start from the changed database by making the changes to the database and the App and uninstalling the App. No need to play with version numbers.
Amend the User class by adding the new surname column. e.g.
:-
#Entity
class User {
#PrimaryKey
#NonNull
String name;
String profession;
int age;
String description;
/* ADDED FOR V2 */
String surname;
}
Compile (Ctrl + F9) and then from Android View located the generated Java and then the class that is then same as the #Database class but suffixed with _Impl.
locate the createAllTables method and then the SQL for the User table. Make a note of the SQL and the definition for the new column e.g. -surname TEXT
In SQLite Studio, run the following SQL:- ALTER TABLE user ADD COLUMN surname TEXT; where the text/code after the COLUMN key word is EXACTLY as per the SQL noted above (you can include or omit the enclosing `'s around the column name, they aren't easy to display in SO)
Look at the Data e.g. it will now be :-
note that the surname column is populated with nulls.
Edit the data accordingly. e.g. :-
Then run the following SQL PRAGMA user_version; (to check the current version)
Then run the following SQL PRAGMA user_version = 2; ( to change the version (guessing 2))
Then run the following SQL PRAGMA user_version; (to check that the version is now 2)
Quit SQLite Studio
Replace the file/asset in the project with the new database. e.g. :-
In the #Database class (NOT the generated java) :-
change the database version to 2
add the following to the the databaseBuild :-
either .fallbackToDestructiveMigrationFrom(1) if going from 1 to 2
or .fallbackToDestructiveMigration() (not as safe but more encompassing)
Run the App and e.g. :-

Related

I converted the database file to a text file

I accidentally converted my database file to a text file. When opened, it shows that I am using the wrong encoding format. Any help would be highly appreciated.
File screenshot
I don't believe that you have because :-
Android Studio has no built-in support for browsing SQLite databases and hence why it shows as it does. It would probably look similar in NotePad.
That is there is little reason why you would open a database in Android Studio (or any other editor (unlesss it is one that supports SQLite files)).
To re-assure you, here's an SQLite database I opened in Android Studio (and goth the same message) :-
If you loaded the file into/opened the file in a tool for browsing/managing SQLite databases then I would expect that the database will be accessible.
Opening the above database in an App allows the App to output the following from the database :-
04-02 10:25:18.979 1837-1837/? D/OADB-HLPR: logDatabaseTableInformation initiated.
Database contains Table testtable created by SQL CREATE TABLE `testtable` (
`_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` TEXT,
`timestamp` INTEGER
)
Table is testtable Column Count = 3 Row Count = 2
Columns are :- _id name timestamp
Database contains Table sqlite_sequence created by SQL CREATE TABLE sqlite_sequence(name,seq)
Table is sqlite_sequence Column Count = 2 Row Count = 1
Columns are :- name seq
logDatabaseTableInformation completed.
As you can see a lot of the information matches the screenshot.
Likewise if you accessed the database in an app then again it very much looks as though it would be as expected.
From what is shown it appears that you have a table called QuestionBank, it has a column with a type of INTEGER PRIMARY KEY AUTOINCREMENT as table sqlite_sequence exists. etc.
I say this because the first characters are SQLite format 3 as per :-
0 16 The header string: "SQLite format 3\000"
Database File Format
One such tool that is commonly used is DB Browser for SQLite.

How to pass SQL query as a context variable in Talend Open Studio job

I am creating a job to pull data from a database to CSV file using talend open studio. There are 100 of tables, the data types and no of columns differ in the tables, I want to pull the data from database tables with a single job and customizable SQL query. I know how to create and use context variables.
If I understood you correctly you should be using tMap's reload at each row -option and defining table names in Excel sheet or in tFixedFlowInput.
tMap settings
Whole job and results
SQL Script:
"SELECT TOP(1) Name, Code from mdm." + (String)globalMap.get("row4.table")
I used Microsoft SQL Server for example but same script works as well with MySQL.
You can simply use a context-variable which you set via the --context_param argument in a tWhicheverDatabaseInput. E.g. define a context variable "my_sql" which you can set in the commandline as
my_job.sh --context_param my_sql="select a,b,c from a_test_table"
and then use context.my_sql as the SQL in you database input component.
However, as garpitmzn already mentioned, you will need dynamic schemas to actually work with this unknown structure in Talend. This feature only exists in the enterprise version.
If the enterprise version is available to you, simply declare a single column of type "Dynamic", which you can pass through the rest of your flow.
Declare a local context say query as type string.
Prepare a context file with variable query: query=select name from employee
Excecute the query: toraclecomponent use context.query
Query is throwing some error when you have where conditions with string type.
Need to investigate more on that. Otherwise it works.

Java program to transfer from SQL database to another in java : column field = reserved word

I am trying to run my java program, in which I have to transfer data from a DB to another one.
Well, the program works but one of the column field is named "public", and when I'm trying to transfer that data using jdbc, it crashes with the following statement:
"incorrect syntax near from keyword 'public'".
I've tried to load the column field as [public], (public), `public` works in SQL syntax but not in the program, since it has to check equivalence for "public", so "'public' is returning false.
Some code sample when i load the datas :
String publicDb = iArboFromExtranet.get(i).getString("public");
Some code sample when i transfer it :
private static final String PUBLIC = "public";
IArbo.set(PUBLIC, Strings.nullToEmpty(publicVar))
By the way, i cant rename the fields since i'm working for IT services industry. Its not our database
Since you're using a framework to generate your SQL, and you use a reserved word as a column name, you have a (tough?) choice to make:
Update the implementation of IArbo to quote reserved words (or all names).
Don't use IArbo.
Don't use a reserved word as a column name.
It looks like you're building SQL insert and/or update queries. Quote everything, so if the database field is MyField and the table is MyTable your query should have "MyTable" and "MyField" for this particular field. In Java you can build the string by escaping the double quote with a backslash:
queryString = "insert into \"MyTable\" (\"MyField\"...) values ('whatever'...)";

insert data using cursor Oracle

Database: Oracle 11gr2;
Web application : JSP(Java)
I have two tables:
Cities(***Id***, Name); Id is the Primary Key
Persons(***IdPers***, Name, IdCity_FK); IdCity is Foreign Key
IdCity_FK reffers to column Id from Cities.
The question: how to insert data from a insert.jsp page which has the following fiels:Person's name, City.
I want the user to enter his name and to select a city from some ListBox dynamically generated (using Cursor Oracle or a other method). For instance, one does not enter : Andrew, 12, but enters Andrew and select New York.
I managed to do this by using Oracle REF CURSOR, but when clicking submit I get error. I think it does not pass an int value as parameter.
The code
create or replace
FUNCTION GET_CITIES
RETURN CITYPKG.ref_cursor
AS cities_cursor CityPkg.ref_cursor;
BEGIN
OPEN cities_cursor FOR
SELECT id, nume FROM CITY;
RETURN CITIES_cursor;
END;
In the JSP page for editing I have a jspforward tag which sends me to a page which handles the form with request.getParameter... and calls a function which has 2 parameters: one is String the other one is int. The int one inserts the corresponding foreign key in the database.
Thank you in advance.
There was an error at JSP file(parameter).

Invalid object name

When doing...
select * from students
I get a "Invalid object name" error. Basically, I think I can see the problem in that the tables are prefixed with an object name rather than just dbo, lets call the schema "test".
So this means....
select * from test.students
The problem I have is that I can't change the SQL code (it's in release, long story) or change the tables. My question is, is there anything I can change in SQL server that will allow me to connect say with a specific SQL server user so I can still run my queries as...
select * from students
Omitting the object name, but still have the object name against the table? I can add another SQL user or something like that no problem.
I'm using Java over the jdbc protocol, so my connection string is something like jdbc:sqlserver://hostname:port;databaseName=db;user=myuser;password=mypassword
Thanks,
David
You're looking for a default schema option, which doesn't exist for a given connection. That is to say that you can't say something like "until I say otherwise, unqualified tables are in the test schema". You can, however, set a default schema for a user. For your example, you'd do
alter user [myuser] with default_schema = [test]
Try to edit the connection string and set your default catalog to your "test" database
<add name="ConnectionString" connectionString="Data Source=server;Initial
Catalog=test;Persist Security Info=True;User ID=user;Password=password;"
providerName="SqlDataClient"/>

Categories

Resources