I have a place where I store tables.
In this place I have a table. Lets' name it Table A. All columns in table A columns are varchars.
I want to create a process that will go through every table and create a new table in a different place in the database.
However this table has to have the right datatypes instead of varchars.
So if my column in table A is a column with the values 1234, I want to create a field that will be an INT an not a varchar.
I don't have any idea how to do it in java. Could somebody point me in the right direction on what things I would have to learn and if it is too difficult
Thanks
As I see it, your problem has a few parts:
EASY - Getting the existing table information. You'll have to get the DatabaseMetaData from your jdbc connection. Documentation on that class is here, and Google is your friend as to how to get that Object in the first place. (Hint: this question should get you most of the way )
MEDIUM - Figuring out what data type your data really is. If you try to narrow it down to just a few simple types like Integer, String, and dates, this might not actually be that hard. You'll just need to select a few rows for each column (where that column isn't null), and then try and parse it into different types. If it succeeds, it probably is that type. If it throws an Exception, then it's not. Integer.parseInt(), LocalDateTimeFormatter, etc. are the things you'll be using.
If you want to get table meta data, then just do a "SELECT * FROM < TABLE >" and the ResultSetMetaData will have all the information you'll need to keep going.
VERY HARD - Creating tables using the new, appropriate data types. This is hard not because of the stuff that's been mentioned so far, but because we haven't yet talked about foreign keys, indexes, and all that other good stuff. Mapping all those things programmatically will be a very hard problem. Therefore, I recommend NOT trying to program this part. Instead, have your script output the mapping of old datatypes to new datatypes for each table. Then you can go into your SQL mananger and get the SQL script to generate that table. Almost every SQL database management tool can generate the creation script for a table. Edit that script with your new datatypes, give it a new name, and run it.
Related
What's the best approach when it comes to processing data to be inserted to the SQLite database:
1. Write as much of the code with complexTRIGGERSinside the database itself.
2. Dynamically createTEMPORARY TABLESand similar solutions inJava.
3. Do the processing almost entirely inJavawith primitive CRUD statements to manipulate the database?
I don't really have any real code to share, since I'm at conception, but what would the best way to for example enforceFOREIGN KEYS(i.e. delete rows that no longer has a connected value in the referenced table); withTRIGGERSorJava? Another example: would it be better to use theJavamethodlength()instead of the followingTRIGGER?
CREATE TABLE table ( column1 TEXT, column2 INTEGER );
CREATE TRIGGER tableTrigger INSERT ON table BEGIN INSERT INTO table VALUES ( NEW.column1 , LENGTH ( NEW.column1 ));
(Note: these are quite simple examples, and theTRIGGERSI'd end up with would be more complex, so I'm interested in a general approach or applicable rules of thumb.)
This really depends on the specific constraint you are trying to enforce.
For your first example, there is no need to write a trigger to enforce a foreign key relationship. SQLite will add this constraint for you when you define the column, by adding "ON DELETE CASCADE" (read more here: https://www.sqlite.org/foreignkeys.html).
I would tend towards writing the logic in the application code itself, as that will be easier to debug than database triggers.
https://softwareengineering.stackexchange.com/questions/123074/sql-triggers-and-when-or-when-not-to-use-them
I'm relatively new to working with JDBC and SQL. I have two tables, CustomerDetails and Cakes. I want to create a third table, called Transactions, which uses the 'Names' column from CustomerDetails, 'Description' column from Cakes, as well as two new columns of 'Cost' and 'Price'. I'm aware this is achievable through the use of relational databases, but I'm not exactly sure about how to go about it. One website I saw said this can be done using ResultSet, and another said using the metadata of the column. However, I have no idea how to go about either.
What you're probably looking to do is to create a 'SQL View' (to simplify - a virtual table), see this documentation
CREATE VIEW view_transactions AS
SELECT Name from customerdetails, Description from cakes... etc.
FROM customerdetails;
Or something along those lines
That way you can then query the View view_transactions for example as if it was a proper table.
Also why have you tagged this as mysql when you are using sqlite.
You should create the new table manually, i.e. outside of your program. Use the commandline 'client' sqlite3 for example.
If you need to, you can use the command .schema CustomerDetails in that tool to show the DDL ("metadata" if you want) of the table.
Then you can write your new CREATE TABLE Transactions (...) defining your new columns, plus those from the old tables as they're shown by the .schema command before.
Note that the .schema is only used here to show you the exact column definitions of the existing tables, so you can create matching columns in your new table. If you already know the present column definitions, because you created those tables yourself, you can of course skip that step.
Also note that SELECT Name from CUSTOMERDETAILS will always return the data from that table, but never the structure, i.e. the column definition. That data is useless when trying to derive a column definition from it.
If you really want/have to access the DB's metadata programatically, the documented way is to do so by querying the sqlite_master system table. See also SQLite Schema Information Metadata for example.
You should read up on the concept of data modelling and how relational databases can help you with it, then your transaction table might look just like this:
CREATE TABLE transactions (
id int not null primary key
, customer_id int not null references customerdetails( id )
, cake_id int not null references cakes( id )
, price numeric( 8, 2 ) not null
, quantity int not null
);
This way, you can ensure, that for each transaction (which is in this case would be just a single position of an invoice), the cake and customer exist.
And I agree with #hanno-binder, that it's not the best idea to create all this in plain JDBC.
Hello World, Here is the situation,
Basically instead of generating values from a table like like so
34.324, 09/13/2011, thankyou,
I would like to generate the type of that specific value
e.g
VarChar2, Date, varchar2(char 30)
Just to add another layer of difficulty a Java application pulls data from the multiple Oracle database tables using HQL. Thus I would need an equivalent HQL statement to the SQL statement (if it exists)..
I understand the DESC keyword lists the column data types for an entire table however as mentioned above I require specificity.
In Summary
I would like to reverse engineer this application to generate a report of the data_types of the data instead of the actual data itself. I could easily just manually walk through the code however they are over 200 entries and this will be a real pain.
Any help is truly appreciated. If this question is unclear please let me know and I will provide more details and examples.
I have a hashmap with pair.
the key in this are column-names in a table Now I want to insert them into a table say users_table,
i should be able to match the key to the column names and if both are same then insert that value into table.
What I am doing is that i have to write preparedstatement with all the columns and then pass the hashmap values as parameter using setter methods of preparedsatatement.
For doing this i need to know all the columns of table and this would be tedious work as there would be no. columns and this step would be repeated to no.of tables.
tell me Any idea of doing this, Thanks in Advance
First off, use a LinkedHashMap to preserve the order of the columns. This will make a difference when iterating over the map to assign column names and then values.
I'm not entirely sure what you're asking, but you're hinting at what is called Object Relational Mapping (ORM). Simply put, it's a way to map database tables to plain old Java objects (POJO). Though there's a lot more to it than that.
If you're interested in representing your database tables as objects, you should look into Hibernate, which is a popular Java ORM API.
Otherwise, create and keep to a standard that is uniform across both your database and your Java project and you'll be fine.
Edit:
If I understand your question a little more, you're having issues with knowing the names of the columns? This is something you have to know, there's not going to be an easy, dynamic, or efficient way of getting that information.
One example of setting that information is storing the column names in a String array of a class that represents your table. You can then access the array and iterate over it when saving to a database.
And finally, if you feel like doing some reading, check out my answer (Store nested Pojo Objects as individuall Objects in Database). I go quite in-depth on how I manage Database to Java and vice versa.
Im programming a program in java and i have a database in a JTable just like the ones below. I wanted to know if it is possible to refresh the primaryID location from 1 on the GUI interface form one when a row is deleted? for example below the LoactionID is deleted for London and added again with an id 4. Is this possible?
Im using SQL in java
To answer your question, yes it is possible.
There is no good reason for you to do this though, and I highly recommend you don't do this.
The only reason to do this would be for cosmetic ones - the database doesn't care if records are sequential, only that they relate to one another consistently. There's no need to "correct" the values for the database's sake.
If you use these Id's for some kind of numbering on the UI (cosmetic reason):
Do not use your identity for this. Separate the visual row number, order or anything else from the internal database key.
If you REALLY want to do this,
Google "reseeding or resetting auto increment primary ID's" for your sql product.
Be aware for some solutions if you reset the identity seed below values that you currently have in the table, that you will violate the indentity column's uniqueness constraint as soon as the values start to overlap
Thanks Andriy for mentioning my blindly pasting a mysql solution :)
Some examples:
ALTER TABLE table_name ALTER COLUMN auto_increment_column_name RESTART WITH 8 Java DB
DBCC CHECKIDENT (mytable, RESEED, 0)
Altering the sequence