if (Baglan() == false) { return false; }
try{
String generatedColumns[] = {"ID","TAHSILATNO"};
String sSql = "Declare nId number := 0;" +
" nKey number := 0;" +
" BEGIN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, 53);" +
" EXCEPTION " +
" WHEN DUP_VAL_ON_INDEX THEN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" Select Nvl(Max(tahsilatno),0) + 1 INTO nKey From bvktahsilatno WHERE Yili = 2018;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, nKey);" +
"END;";
//VtStatement = VtConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//VtStatement.execute(pSql);
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS );
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, generatedColumns );
PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS);
System.out.println("oracle cumle : " + sSql);
int nAdet = VtStatement.executeUpdate();
System.out.println("Hatayok/Adet : " + nAdet);
ResultSet rs = VtStatement.getGeneratedKeys();
int id=0;
while (rs.next()) {
id = rs.getInt(1);
}
System.out.println("Oracle Inserted ID -" + id); // display inserted record
return true;
} catch (SQLException e) {
return false;
}
I want to ask a question about retrieving created keys on Oracle Db after insert query. My code is as above but generated keys values are not showed on the terminal. How can i get generated column values without creating sequence ? Many form pages say that it is possible as using sequence for id or other column. Also id is primary key, tahsilatno is unique index. I can overcome this problem?
Thank you for your helping from now
Related
public class DataBase {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/company", , )) {
Type[] types = { new GraphicCard(), new HardDrive(), new Keyboard(), new Memory(), new Monitor(), new Mouse(), new Processor() };
Product product = new Product(10, types);
Range rangeUnitPrice = new Range(10_000, 220_000);
Range rangeQuantity = new Range(0, 20);
Statement statement = connection.createStatement();
while (product.getNumberOfEntery() > 0) {
String typeAndCatagory = product.getRandomType();
String name = product.getName(typeAndCatagory);
String description = product.getDescription();
double unit_Price = product.randomUnit_PriceGenerator(name, 'x', rangeUnitPrice);
int quantity_In_Stock = product.generateQuantity_In_Stock(rangeQuantity);
String brand = product.getRandomBrand();
System.out.println("Name: " + name + ", " + "Type: " + typeAndCatagory + ", " + "Random price: " + unit_Price + ", " + "Quantity in stock: " + quantity_In_Stock + ", " + "Random brand: " + brand);
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
statement.executeUpdate(query);
product.decreasesNumberOfEntrees();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The query doesn't work, and the first value is the default (PRIMARY KEY AUTO-INCREMENT), which I don't need to specify. The error is below
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near '10 AMD graphic card Gamer Edition, ,
180657.63138583858, 6, HP, Graphic Card, Gr' at line 1
You format a string in this line to use as an SQL statement:
String query = "INSERT INTO product VALUES (" + name + ", " + description + ", " + unit_Price + ", " + quantity_In_Stock + ", " + brand + ", " + typeAndCatagory + ", " + typeAndCatagory + ")";
Something is wrong with this statement that makes it produce a syntax error. What is wrong?
It's difficult to debug this by staring at the Java expression. It's confusing to look at all the " and + and see what's wrong.
It would be easier to see what's wrong if you can see the final result of the string, not the Java expression that builds a string.
So before you execute it, try printing it out:
System.out.println(query);
Then the problem may be more clearly visible.
I predict it will look something like this:
INSERT INTO product VALUES (10 AMD graphic card Gamer Edition, , 180657.63138583858, 6, HP, Graphic Card, Gr...
This is missing quotes around the string values in your VALUES clause. It's not valid SQL.
The best solution is to learn to use query parameters. Then you don't have to worry about quotes around values. And the code is more secure from SQL injection.
In your case, something like the following:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?, ?, ?)";
Statement statement = connection.prepareStatement(query);
while (product.getNumberOfEntery() > 0) {
// set the values for all your variables...
statement.setString(1, name);
statement.setString(2, description);
statement.setDouble(3, unit_Price);
statement.setInt(4, quantity_In_Stock);
statement.setString(5, brand);
statement.setString(6, typeAndCatagory);
statement.setString(7, typeAndCatagory);
statement.executeUpdate();
}
There are two problems with your code:
The major one is, your code is vulnerable to SQL Injection.
You will have to enclose the text values withing single quotes yourself.
The solution to both the problem is using PreparedStatement as shown below:
String query = "INSERT INTO product VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = con.prepareStatement(query)) {
//...
pstmt.setString(1, name);
pstmt.setString(2, description);
pstmt.setDouble(3, unit_Price);
//...
pstmt.executeUpdate();
}
Also, I suggest you always follow Java naming conventions e.g. unit_Price should be named as unitPrice.
Those are the SQL tables I am taking the data from
String sql = "CREATE TABLE IF NOT EXISTS term_index (\n"
+ " term_id integer PRIMARY KEY AUTOINCREMENT ,\n"
+ " term text ,\n"
+ " multiterm integer \n"
+ ");";
execute(sql);
sql = "CREATE TABLE IF NOT EXISTS doc_term (\n"
+ " term_id integer ,\n"
+ " wiki_id text ,\n"
+ " section text ,\n"
+ " freq integer ,\n"
+ " tfidf double ,\n"
+ " cvalue double ,\n"
+ " rake double ,\n"
+ " PRIMARY KEY (term_id, wiki_id, section) \n"
+ ");";
execute(sql);
This is the SQL statement to take the termIDs from the tables above
/**
*
* #param wikiID
* #return
*/
public HashSet<Integer> getWholeDocumentTermIDs(String wikiID) {
HashSet<Integer> termIDs = new HashSet<Integer>();
String sql= "SELECT term_id FROM doc_term WHERE wiki_id = ?";
try {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,wikiID);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String sql2= "SELECT term_id, multiterm FROM term_index WHERE term_id = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
//System.out.println(rs.getInt("term_id"));
int term_id = rs.getInt("term_id");
if(term_id != 0) {
stmt2.setInt(1,term_id);
ResultSet rs2 = stmt2.executeQuery();
int multiterm = rs2.getInt("multiterm");
if(multiterm == 0) {
termIDs.add(term_id);
}
rs2.close();
}
}
rs.close();
} catch (SQLException e) {
System.out.println(e.getMessage() + "in getWholeDocumentTermIDs");
}
return termIDs;
}
The function getWholeDocumentTermIDs(String wikiID) is called 30 k times, meaning for 30 k wikiIDS, so when executing this, steadily more and more RAM is used by my IDE, starting at roughly 1,3 GB to later up to 10 or 11 GB, at which point the process starts to slown heavily. My question is if and how I can reduce/clean up the RAM to fetch all the required data stored in those tables.
I need to get a single value from SQLite database. I have 2 tables connected in a multiple way and between them is a middle table. I need to get a value from the middle table, but I am always getting an error and don't understand what I am doing wrong.
This is the hashcode and error:
ResultSet#12c6d7d2
Exception in thread "AWT-EventQueue-0"
java.lang.NumberFormatException: For input string:
"org.sqlite.jdbc4.JDBC4ResultSet#12c6d7d2"
Here is the method:
public int stockProducts(String warehouse, String product){
String sqlSelectStock = "select piw.Stock from ProductsInWarehouse as piw " +
"where piw.idWarehouse in (select w.id from Warehouseas w " +
"where w.nameWarehouse = '" + warehouse + "') " +
"and piw.idProducts in (select p.id from Products as p " +
"where p.nameProduct = '" + product + "');";
ResultSet result = null;
int count = 0;
try {
stmt = povezava.createStatement();
result = stmt.executeQuery(sqlSelectStock);
count = Integer.parseInt(result.toString());
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
result is a ResultSet object and not a String.
This ResultSet object contains the rows returned by the query that you execute.
You must loop (if you are expecting more than 1 rows) through the rows of result and extract the value of the column Stock so you can parse it to an Integer.
I assume (by your code) that you are expecting only 1 row, so change to this
stmt = povezava.createStatement();
result = stmt.executeQuery(sqlSelectStock);
String stock = "0";
if (rs.next()) {
stock = result.getString("Stock");
}
count = Integer.parseInt(stock);
I am trying to get matricule of every item on the JList and the stage_ID from a JTextField and insert them in the table employé_stage that contains only two columns stage_ID and matricule as foreign keys respectively referencing the tables stage and employés. I want all the records from JList to be inserted in the table employé_stage with the same stage_ID I'm using this code that returns can not add or update child row: foreign constraint fails
private void addstageActionPerformed(java.awt.event.ActionEvent evt){
try{
for (int i = 0; i < stagelist.getModel().getSize(); i++) {
String item = stagelist.getModel().getElementAt(i).toString();
String[] items =item.split(" ");
if(items.length >= 2){
String sql ="INSERT INTO stage (nature,datedebs,datefs,durée_S,commentaire,stage_ID) values(?,?,?,?,?,?) ";
String sql2="INSERT INTO employé_stage (matricule) Select matricule from employés where nom='"+items[0]+"' and prénom='"+items[1]+"' ";
String sql3="INSERT INTO employé_stage (stage_ID) select LAST(stage_ID)from stage ";
ps2 = conn.prepareStatement(sql2);
ps3 = conn.prepareStatement(sql3);
ps = conn.prepareStatement(sql);
ps.setString(6,stageID.getText());
ps.execute();
ps2.execute();
ps3.execute();
}
}
} catch(Exception ev){
JOptionPane.showMessageDialog(null, ev);
}
miseajour_tab();
}
You are getting the foreign key exception because sql2 and sql3 are inserting one record each, and the foreign key constraints require that both fields be populated in each record.
You must merge these two into one insert statement like:
String sqlboth="INSERT INTO employé_stage (stage_id, matricule) " +
"( " +
" select LAST(s.stage_ID), e.matricule from stage s, employés e " +
" where e.nom='"+items[0]+"' and e.prénom='"+items[1]+"'" +
")";
Further, you should use placeholders in the insert so you are not vulnerable to SQL injection attacks.
String sqlboth="INSERT INTO employé_stage (stage_id, matricule) " +
"( " +
" select LAST(s.stage_ID), e.matricule from stage s, employés e " +
" where e.nom=? and e.prénom=?" +
")";
PreparedStatement psboth = conn.prepareStatement(sqlboth);
psboth.setString(1, items[0]);
psboth.setString(2, items[1]);
psboth.executeUpdate();
i tried with this piece of code, it works but it only inserts the first record of th JList :
private void addstageActionPerformed(java.awt.event.ActionEvent evt) {
try{
for (int i = 0; i < stagelist.getModel().getSize(); i++) {
String item = stagelist.getModel().getElementAt(i).toString();
String[] items =item.split(" ");
if(items.length >= 2){
String sql2="INSERT INTO employé_stage (stage_id, matricule) " +
"VALUES ( " +
" ?, " +
" (Select matricule from employés where nom='"+items[0]+"' and prénom='"+items[1]+"')" +
")";
ps2 = conn.prepareStatement(sql2);
ps = conn.prepareStatement(sql);
ps2.setString(1,stageID.getText());
ps.execute();
ps2.execute();
}}
} catch(Exception ev){
JOptionPane.showMessageDialog(null, ev);
}
miseajour_tab();
}
I get the following MySQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'book.call_Number' in 'field list'.
What does that mean and how can I solve it?
Here is the code responsible for this exception:
public void actionPerformed(ActionEvent e) {
list.clearSelection();
String selectString = " ";
String afName = auth_fName.getText();
String aMI = auth_MI.getText();
String alName = auth_lName.getText();
String tField = titleField.getText();
String sField = subjectField.getText();
try {
Connection conn = Database.getConnection();
Statement s = conn.createStatement();
if (!afName.equals("") && (!aMI.equals("")) && (!alName.equals("")) && (!tField.equals("")) && (!sField.equals(""))) {
selectString = "SELECT a.call_Number as callNbr "
+ "FROM book a "
+ "FULL JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
}
s = conn.createStatement();
System.out.println(selectString);
ResultSet rs = s.executeQuery(selectString);
while (rs.next()) {
String call_Num = rs.getString("call_Number");
String title = rs.getString("title");
String auth_lName = rs.getString("auth_lName");
String auth_MI = rs.getString ("auth_MI");
String auth_fName = rs.getString("auth_fName");
String availability = rs.getString("availability");
view = new View(call_Num, title, auth_lName, auth_MI, auth_fName, availability);
vList.add(view);
System.out.println(view);
}
rs.close();
s.close();
conn.close();
list.setListData(vList.toArray());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here is the DDL and content:
s.executeUpdate (
"CREATE TABLE book ("
+ "call_Number CHAR(10),"
+ "PRIMARY KEY (call_Number),"
+ "auth_fName CHAR(30)NOT NULL, auth_MI CHAR(2),"
+ "auth_lName CHAR(50)NOT NULL, title CHAR(100) NOT NULL,"
+ "subject CHAR(30) NOT NULL)");
count = s.executeUpdate (
"INSERT INTO book"
+ " VALUES"
+ "('MY.111.000', 'Mark', 'M','Bradshaw','Mystery Under the Sun','mystery'),"
+ "('MY.111.001', 'Mark','','Twain','The Adventures of Huckleberry Finn','mystery'),"
+ "('SF.111.002', 'Kito', 'M','Bradford','Mr. Roboto','science fiction'),"
+ "('SF.111.003', 'Eric','','Laslow','Science Fiction - Can It Happen?','science fiction'),"
+ "('AV.111.004', 'Rashad','','Cheeks','Fire Under the Bridge','adventure'),"
+ "('AV.111.005', 'Samantha','A','Appleby','The Open Sea','adventure'),"
+ "('CO.111.006', 'Lindsey', '','Butterby','What? We cant spend anymore!?','comedy'),"
+ "('CO.111.007', 'Judy', 'S','Yates','So this is life?','comedy'),"
+ "('IN.111.008', 'Elizabeth', 'J','Lee','Mystery Under the Sun','international'),"
+ "('IN.111.009', 'Gabriella', 'M','Rodriguez','Love in Brazil','international')");
*******t_action table***************************
//create transaction table
s.executeUpdate (
"CREATE TABLE t_action ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "avail CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO t_action"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-03-08','2011-03-15','AVAILABLE',5.00),"
+ "('P222200001','MY.111.001','2011-03-31','2011-04-6','DUE 2011-04-6',5.00),"
+ "('P222200002','SF.111.002','2011-03-30','2011-04-5','DUE 2011-04-5',5.00),"
+ "('P222200003','SF.111.003','2011-03-29','2011-04-4','DUE 2011-04-4',5.00),"
+ "('P222200004','AV.111.004','2011-03-28','2011-04-3','DUE 2011-04-3',5.00),"
+ "('P222200005','AV.111.005','2011-03-27','2011-04-2','DUE 2011-04-2',5.00),"
+ "('P222200006','CO.111.006','2011-03-26','2011-04-1','DUE 2011-04-1',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','AVAILABLE',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','AVAILABLE',5.00),"
+ "('P222200009','IN.111.009','2011-03-06','2011-03-12','AVAILABLE',5.00)");
Use a <column> as predicate like below:-
selectString = "SELECT a.call_Number as callNbr, ... "
+ "FROM book a"
+ "FULL JOIN transaction b"
+ "ON a.call_Number=b.call_Number";
And then change the code to look for callNbr :-
String call_Num = rs.getString("callNbr");
HTH.
Change your query to this:
selectString = "SELECT a.call_Number "
+ "FROM book a "
+ "INNER JOIN transaction b "
+ "ON a.call_Number=b.call_Number";
MySQL does not support FULL OUTER JOIN. If you really need the effect of that - you'll need 2 selects with a UNION. Although from looks of it - does not seem like that would be necessary.