Netezza JDBC MetaData information for DISTRIBUTE clause - java

Is there a way to retrieve the DISTRIBUTE clause from a Netezza table using JDBC MetaData?

After some searching, I found a temporary work around based on the link below:
http://pic.dhe.ibm.com/infocenter/ntz/v7r0m3/topic/com.ibm.nz.adm.doc/r_sysadm_user_views.html
The code below does the job, however not through DatabaseMetaData
String SQLString = "SELECT ATTNAME FROM _V_TABLE_DIST_MAP\n";
SQLString += "WHERE TABLENAME = '" + table + "'\n";
SQLString += "ORDER BY DISTSEQNO";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(SQLString);
while( rs.next() ) {
System.out.println(rs.getString(1));
}
rs.close();

Related

Insert int value of Resultset in SQL-Database

I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!

JDBC does not Inserting data into mysql table

I have problem with inserting data into mysql table. JDBC doesnt inserting data into mysql table.
JDBC should get value from input "liczbaUzytkownikow" and "data from table form which contains informations about "termin" (Exactly: termin.nazwaObiektu, termin.adresObiektu, termin.dzien, termin.odKtorej and termin.doKtorej).
Here is code of this JDBC:
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
Any suggestions ?
You should use PreparedStatement to avoid sql injection attacks.
Furthermore your sql is wrong:
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
you cannot execute two different statements in a single batch.
In your case an Insert and an Update.
Create two PreparedStatement's:
String sql1 = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values (?,?)";
String sql2 = "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = ?";
PreparedStatement preparedStatement1 = con.prepareStatement(sql1);
preparedStatement1.setString(1, liczbaUczestnikow );
preparedStatement1.setInt(2, idTerminal);
PreparedStatement preparedStatement2 = con.prepareStatement(sql2);
preparedStatement2.setInt(1, idTerminal);
preparedStatement1.executeUpdate();
preparedStatement2.executeUpdate();

Dynamic Delete query

Im trying to make a dynamic Delete Query.
What im basically trying to do is first grab the name of the first column in any table (the primary key). Then i use that in Another Query to delete from that table though i get a nullpointerexception?
Ohh and the primary key is not an INT like 1,2,3,4,5 etc.. it's formed up as S1,S2,S3,S4,S5 etc and has the type TEXT.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+tablename+" WHERE " +FirstColumn+ " = " +row;
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
I am going to assume that all the variables you are using have been initialized.
I added single quotes around the FirstColumn name.
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
FirstColumn = rsmd.getColumnName(1);
String query = "DELETE FROM "+ tablename +" WHERE " + FirstColumn + " = '" + row + "'";
stmt = c.createStatement();
stmt.executeUpdate(query);
stmt.close();
c.close();
If you are still getting an error you should try printing out your row name and see what it prints out.
Edit: Since you are new stylistically it's preferable to add a single space when using operators to improve code readability. For example 1+3+x+34 is a lot harder to read than 1 + 3 + x + 34. Granted there is no "wrong" code style but improving code readability is always a plus.
Initialize your stmt object...
stmt = c.createStatement();
before executing the query.

simple query: not implemented by SQLite JDBC driver

First crack at using SQLite+Java and I'm recieving an error when I attempt to execute a simple simple query.
Error:
not implemented by SQLite JDBC driver
Query:
String sql =
"select Asset, Qty*Price+Fees as Cost \n" +
"from Transactions t \n" +
" inner join TransactionItems i on t.Id = i.TransactionId \n" +
"where TransDate <= ? \n";
try (PreparedStatement stmt = cnn.prepareStatement(sql)) {
java.sql.Date dte = new java.sql.Date(SumDate().getTimeInMillis());
stmt.setDate(1, dte);
try(ResultSet rs = stmt.executeQuery(sql)) {
while(rs.next()) {
PortfolioSummaryItem item = new PortfolioSummaryItem(PortfolioSummary.this);
item.Load(rs);
items.put(item.asset,item);
}
rs.close();
}
stmt.close();
This was a simple cut/paste style error. When using prepared statements, you shouldn't then pass the SQL into the executeQuery.
Change:
try(ResultSet rs = stmt.executeQuery(sql)){
To:
try(ResultSet rs = stmt.executeQuery()){
This was overriding the preparedStatement.
What it was complaining about was executing a query with a '?' in it since it wasn't the prepared query.
Check the jdbc driver you have in the libs folder.
It looks like it has not implemented the methods you have called.
Try downloading the driver from here:
https://bitbucket.org/xerial/sqlite-jdbc/downloads

Querying to Oracle DB through JDBC gives null while direct query gives the output

I have a sql query which when I manually sends to an Oracle DB through SQLDeveloper Application gets me the output I want. But the same query returns nothing while I try to connect and query through JDBC driver why this is happening so. Please help me.
code:
String sql = "select * from tablename where id='" + id + "' AND case_id = '" + case_id + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("next = " + rs.next());
output:
select * from tablename where id='1' AND case_id = '1000'
next = false
Both connections (JDBC and SQLDeveloper) are using same username and password. So no issue of privilege or security i think.
Try to pass the "id" as a number. As you are passing the ID as String, the JDBC driver will convert it to CHAR, VARCHAR, or LONGVARCHAR.
String sql = "select * from tablename where id=" + id + " AND case_id = '" + case_id + "'";
Resulting string:
select * from tablename where id=1 AND case_id = '1000'
Consider to use PreparedStatement with bind parameters, to avoid sql injection:
String sql = "select * from tablename where id = ? AND case_id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "1000");
ResultSet rs = ps.executeQuery();
References:
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

Categories

Resources