I've created a very simple table, and am attempting to insert into it. The table exists, but nothing I try to insert sticks; the resultSet is always null. I think I'm auto-incrementing my primary key correctly. Any ideas? Thank you!
String createGenreTableSQL = "CREATE TABLE Genre (GenreID INTEGER NOT NULL GENERATED ALWAYS " +
"AS IDENTITY (START WITH 1, INCREMENT BY 1), genreName varchar(60))";
statement.executeUpdate(createGenreTableSQL);
String prepGenreInsert = "INSERT INTO Genre(genreName) VALUES (?)";
psInsert = conn.prepareStatement(prepGenreInsert);
allStatements.add(psInsert);
psInsert.setString(1,"Television");
psInsert.setString(1,"Movies");
psInsert.setString(1,"VideoGames");
psInsert.setString(1,"Animes");
String fetchAllDataSQL = "SELECT * from Genre";
resultSet = statement.executeQuery(fetchAllDataSQL);
while (resultSet.next()) { //resultSet shows null
int genreID = resultSet.getInt("genreID");
String genreName = resultSet.getString("genreName");
System.out.println("GenreID:" + genreID + " Name: " + genreName);
}
The setString method simply binds the given value to the given parameter index. It does not actually execute the query. I believe what you want to do is
psInsert.setString(1,"Television");
psInsert.execute();
psInsert.setString(1,"Movies");
psInsert.execute();
psInsert.setString(1,"VideoGames");
psInsert.execute();
psInsert.setString(1,"Animes");
psInsert.execute();
Related
This is my database:
dragons
id, key, name, age, creation_date
users
id, name, user, pass
users_dragons
user_id, dragon_id
So this is my code for deleting dragons from the database that have a bigger key that the passed and belongs to a determination user. The SQL query works perfectly for deleting them but not for returning the array of keys from the deleted elements.
I tried using PreparedStatement but later I checked, as far as I know, that this class doesn't return arrays, and the CallableStatement is only for executing processes in the db, and I don't know how they return arrays.
String query = "" +
"DELETE FROM dragons " +
"WHERE id IN (SELECT d.id FROM dragons d, users u, users_dragons ud" +
" WHERE d.key > ?" +
" AND ud.dragon_id = d.iD" +
" AND ud.user_id in (select id from users where id = ?)) RETURNING key INTO ?";
CallableStatement callableStatement = connection.prepareCall(query);
int pointer = 0;
callableStatement.setInt(++pointer, key);
callableStatement.setInt(++pointer, credentials.id);
callableStatement.registerOutParameter(++pointer, Types.INTEGER);
callableStatement.executeUpdate();
return (int []) callableStatement.getArray(1).getArray();
The code is giving me the error, but is obvious because the CallableStatement needs a postgres function to run and not a simple SQL query
org.postgresql.util.PSQLException: This statement does not declare an OUT parameter.
Use { ?= call ... } to declare one.
at org.postgresql.jdbc.PgCallableStatement.registerOutParameter
.......
It would be really helpful how would be the correct JDBC algorithm to delete the elements from the database and return the array of keys of the deleted items.
You treat such a statement like a normal SELECT statement: use java.sql.PreparedStatement.executeQuery() or java.sql.Statement.executeQuery(String sql) to execute the statement and get a result set.
java.sql.CallableStatement is for calling Procedures (but you don't need it in PostgreSQL).
I am working on a option in a Menu function that posts the car for the sale in a database. The option asks for the user to enter the year, make, condition and price, which is then inserted into the table car_sale in the database. However, a unique listing_no must also be generated during this option. I cannot define my tables to uniquely generate the 10 digit number the option but I must code the program to insert uniquely generated listing_no. Below you will find the code of me trying to do this, however the code only works in Oracle but I cannot use Oracle. I can only PostGreSQL and Java. Therefore, my problem arises as the functions and relations I am using cannot be used in PostGre.
Code to Generate Listing No:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Code in The Option Function to insert the lisitng_no generated from generateListingNo()
public void option() throws SQLException
{
int listing_no = generateListingNo();
// insert information into books_for_sale table
sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
+ "'" + year + "'" + ", " +
"'" + make + "'" +", " +
"'" + condition + "'" + ", "
+ price + ")";
Erros I am Getting:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
Position: 69 at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:281)
Creating the car_sale table
create table car_sale(
listing_no int not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
Change you query for generateListingNo as below:
select q from (select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ') )q )sq
or
select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval
or on your cocde:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Since you dont have sequence :
Either create sequence using below query:
CREATE SEQUENCE public."AUDIT_SEQ"
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
or use UUID:
public String generateListingNo() throws SQLException
{
return UUID.randomUUID().toString();
}
your table structure will need to change :
create table car_sale(
listing_no varchar not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
For PostgreSQL, you have to call query this way from java :
SELECT nextval('ACCOUNT_TRANSACTION_NO')
String sql2="if not exists(select * FROM stock where productCode=?)\n" +
"Begin\n" +
"insert into stock "
+ "(productName,quantity,currentQuantity,price,companyName,categoryName,productCode) "
+ "values(?,?,?,?,?,?,?)\n" +
"End";
PreparedStatement pst2 = con.prepareStatement(sql2);
pst2.setString(1,productCodeTextField.getText());
pst2.setString(2,productNameTextField.getText());
pst2.setString(3,quantityTextField.getText());
pst2.setString(4,quantityTextField.getText());
pst2.setString(5,priceTextField.getText());
pst2.setString(6, (String) companyNameJComboBox.getSelectedItem());
pst2.setString(7, (String) categoryNameJComboBox.getSelectedItem());
pst2.setString(8,productCodeTextField.getText());
int x=pst2.executeUpdate();
if(x!=0){
productCodeTextField.setText("");
productNameTextField.setText("");
quantityTextField.setText("");
priceTextField.setText("");
JOptionPane.showMessageDialog(null,"Product entered");
}else{
JOptionPane.showMessageDialog(null,"Product already exists");
}
I am successfully able to check for for already existing products before insertion but i am not able to populate the correct message on the basis of the query executed. The executeUpdate is always returning some value even when the insertion is not being done. How to fix this.
There is an easier solution that may work for you:
Throw away the first query that checks whether the entry already exists
Rewrite sql2 as follows:
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
VALUES (?,?,?,?,?,?)
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
Add: pst.setString(7, productCodeTextField.getText());
executeUpdate() returns an int indicating the number of rows affected by the query. Use this variable to determine if a row was added. If the variable != 0 display success message.
INSERT INTO stock
(productCode, productName, quantity, price, companyName, categoryName)
select ?,?,?,?,?,?
WHERE NOT EXISTS
(SELECT * FROM stock WHERE productCode = ?)
This is how it works for SQL Server. 3 and 4 points same as Coop answered
In my current project, I have a function with argument (e.g., int badgID in the following code snippet). This function connects with Apache Derby database, creates table (e.g., FIRSTTABLE), then query to FIRSTTABLE table. The query statement uses function argument for query (e.g., ID = $badgeID ). My question:
Is ID = $badgeID the right way from a syntax point of view?. I have tried this case, but it is not working.
public void getprofile (int badgeID) {
// Create connection with Apache-Derby Database.
// Create table in Apache Derby datbase.
String createString = " CREATE TABLE FIRSTTABLE "
+ "(ID INT PRIMARY KEY, "
+ "PREF INT, "
+ " NAME VARCHAR(12))";
// SQL query on table
querystmt = "SELECT * FROM FIRSTTABLE WHERE ID = $badgeID"
}
that's php syntax...
in java you would write
String querystmt = "SELECT * FROM FIRSTTABLE WHERE ID = " + badgeID;
I have column family that have two primary keys
"CREATE TABLE compositkeys(user_name varchar," +
"user_id int,"+
"name varchar," +
"gender varchar," +
"PRIMARY KEY (user_name,user_id)" +
")";
I have created this in Java now i inserted 6 rows with on one user_name(sunil) primarykey with different id now when I try to retrieve all the value in sunil primary key it gives me only one detail
String qry = "select * from compositkeys where user_name = 'sunil' order by user_id";
Statement smt = con.createStatement();
//smt.executeUpdate(qry);
ResultSet rs = smt.executeQuery(qry);
//rs.get
int r = rs.getRow();
System.out.println(r);
ResultSetMetaData rm = rs.getMetaData();
int columnCount = rm.getColumnCount();
System.out.println(columnCount);
for(int i=1;i<=columnCount;i++)
{
String name = rm.getColumnName(i);
System.out.print(rm.getColumnName(i));
System.out.println(" = "+rs.getString(name));
System.out.println("--------------------------------------------------");
}
It gives me only one output. Is there any thing wrong in query? I want all the data under the key sunil.
You have a single loop that loops over the columns in a returned row, but you only ask for one row (that's the rs.getRow() method). You should put the rs.getRow() call and the following logic to write the results into an outer loop that iterates as long as getRow() doesn't return null. This out loop is what will retrieve all of a user's ids.