How can I convert the JDBC resultset data into Insert queries? - java

I want to convert the records in the JDBC resultset into insert queries for some purposes.
Is it possible? If it is pls suggest me the solution.

Here is a question about generating CREATE TABLE query from ResultSet.
How to create table based on JDBC Result Set
With some changes you should be able to adapt it for an INSERT query also.
Note that, the values have to be added with quotes or with date conversion function etc. as per the data type of the column.
Also, large objects such as CLOB would require some additional bit of work to make them work.

You can use pure SQL for this.
As MySQL docs says:
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can use a select subquery with an insert in other SQL dialects also.

Based on my understanding on your quesstion, You can try like this
try{
ps=con.prepareStatement("select * from login");
rs=ps.executeQuery();
while(rs.next())
{
ps=con.prepareStatement("insert into table2(uname,pswd) values(?,?)");
ps.setString(1,rs.getString(2));// 2-column number
ps.setString(2,rs.getString(3));//3-column number
ps.executeUpdate();
}
}catch(Exception e)
{
System.out.println(e);
}

Related

Is it safe to use JDBC setString() to store CLOB data type with Oracle database?

I have a need to store a large string into Oracle database the length of which would be at most 10000 bytes. I understand that there is some configuration in Oracle 12c that can increase the 4000 byte limit of varchar2. But I do not have the option to use that configuration.
So I am inclined to use the CLOB data type. I have no previous experience in using CLOB. So I have my concerns.
I saw the following on SO
Java: How to insert CLOB into oracle database
I did not want to use any oracle package to handle the CLOB type. My question is, is the following safe enough for my purpose?
To store:
try {
String myclobstring = "xx ........";
String sql = "Insert into mytable (clobfield) values (?)";
Statement stmt = conn.prepareStatement(sql);
stmt.setString(1, myclobstring);
.
.
}
To Retrieve:
try {
String sql = "select clobfield from mytable";
stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(sql);
String s = result.getString ("clobfield');
.
.
}
You can create the CLOB as a String, though using a stmt.setCharacterStream might be a bit better for something very large. Here is an example I found that shows this nicely:
Storing Clobs
You can also use the java.sql.Clob if you're wanting to not use the Oracle specific code.
From Oracle's documentation on CLOB
Use the java.sql.Clob and create the CLOB with the connection's createClob function.
I thought I will post an answer as I did not see an explicit answer. So far setString()/setString() is storing up to 10K characters into the CLOB field. I am getting back what I am storing without a problem.
I did see the following related SO post that gives me a bit more confidence.
How to use setClob() in PreparedStatement inJDBC

How to get column count in SQL before executing the query? i.e. way other than ResultSetMetaData

I have a sql query. Because of too many BO's are involved, it's forming very big query containing more than 1000 columns. So I need some way with which I can find column count before hand and then apply some logic to handle 1000 column error.
May be parsing a query to get column count would help. But not getting how to implement it.
Note: tried below code already, it's giving me result, but i dont want to execute query, that's costly.
PreparedStatement pstmt;
try {
pstmt = getConnection().prepareStatement(sql);
ResultSetMetaData meta = pstmt.getMetaData();
System.out.println(meta.getColumnCount());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If it is a plain old select query like :
select col1,col2 as xyz, col3,col4... from ... where ...
you can do something like this:
String select="select";//"SELECT" if yours is in caps
String from="from";//"FROM" if yours is in caps
String cols = sql.substring(sql.indexOf(select)+select.length(), sql.indexOf(from));
int colCount = cols.split(",").length;
If your query contains functions like fn(col,'blah blah') you need to write some extra code to ID such functions and process things appropriately.
I guess your SQL query using lot of wildcards after SELECT statement right? If no wildcard used, you can parse SQL query part between SELECT and FROM to get column numbers.I feel some disturbance in the force if i hear you have such big results of unknown attributes. If we can say that SQL table is data source, we can say that query result is data source too. In case of SQL table we have defined very specifically what columns(attributes) it contain. If u create SQL query without specification of columns you have data source of unknown entity. Are you trying to create some BI system? If yes you should consider to get metadata of table and create specific query based on this informations.

PGSQL/Java - Inserting data to different tables dynamically

So, I'm trying to insert data to a database completely dynamically, meaning the data will be inserted without any knowledge of what table we're inserting into. The same goes for the different attributes.
My problem is that for some reason, my table names get wrapped in '' when preparing the statment. It goes as follows:
String query = "INSERT INTO ? VALUES(?)";
try{
Connection conn = Connection.create();
PreparedStatment st = conn.prepareStatement(query);
st.setString(1, "test");
st.setString(2, "1");
st.addBatch();
//... (executes batch later on...)
catch (Exception e){
e.printStackTrace();
}
finally{
DbUtils.closeQuietly(rs);
DbUtils.closeQuietly(conn);
}
Now for some reason, and completely beyond me, if I print this statement I get:
"INSERT INTO 'test' VALUES("1");
while I would expect
"INSERT INTO test VALUES("1");
Could anyone explain why this happens and how I can solve this, or a better way to achieve what I'm trying to do? If it matters I'm using DbUtils to handle closing, and 3CP0 for connection pooling.
I have been looking all over without any luck. And I would also appreciate it if anyone could tell me if inserting data dynamically to different tables generally is a bad thing.

Which one to use - executeUpate or list - to insert and update and select?

I've written a stored procedure with the following sql statements
insert a row in table a
update a row in table b
insert a row in error table
select query to list the number of records in the error table
Can i use query.list() ? Will it does all the inserts, updates and returns the list properly?
I think we cannot use query.executeUpdate() as it returns only number of rows updated or inserted at last sql statement.
Thanks in advance,
Kathir
If it is stored procedure you can use do like this
try
{
con = connectionPool.getConnection();
proc = con.prepareCall("{ call set_death_age(?, ?) }");
proc.setString(1, dyingBard.getName());
proc.setInt(2, age);
proc.execute();
}
catch (SQLException e) {}
http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
See above link for sample of how to call stored procedures with hibernate
if you are using spring, you can call stored procedures via Spring JdbcTemplate as well.

How to search and insert a value using java code?

String link = "http://hosted.ap.org";
I want to find whether the given url is already existing in the SQL DB under the table name "urls". If the given url is not found in that table i need to insert it in to that table.
As I am a beginner in Java, I cannot really reach the exact code.
Please advise on this regard on how to search the url in the table.
I am done with the SQL Connection using the java code. Please advise me on the searching and inserting part alone as explained above.
PreparedStatement insert = connectin.preparedStateme("insert into urls(url) vlaues(?)");
PreparedStatement search = connectin.preparedStateme("select * from urls where url = ?");
search.setString(1, <your url value to search>);
ResultSet rs = search.executeQuery();
if (!rs.hasNext()) {
insert.setString(1, <your url value to insert>);
insert.executeUpdate();
}
//finally close your statements and connection
...
i assumed that you only have one field your table and field name is url. if you have more fields you need to add them in insert query.
You need to distinguish between two completely separate things: SQL (Structured Query Language) is the language which you use to communicate with the DB. JDBC (Java DataBase Connectivity) is a Java API which enables you to execute SQL language using Java code.
To get data from DB, you usually use the SQL SELECT statement. To insert data in a DB, you usually use the SQL INSERT INTO statement
To prepare a SQL statement in Java, you usually use Connection#prepareStatement(). To execute a SQL SELECT statement in Java, you should use PreparedStatement#executeQuery(). It returns a ResultSet with the query results. To execute a SQL INSERT statement in Java, you should use PreparedStatement#executeUpdate().
See also:
SQL tutorial
JDBC tutorial

Categories