sqlite function that delete row (java) - java

I am an SQL beginner. I have to write in sqlite a function that gets a db file. The db file contains a lot of tables. The function needs to search in the age column. When there is a age that lower than 20 I need to delete the row.
for example:
first table:
age - name
40 - Din
12 - Tayler
60 - George
second table:
id - name - country - age
1 - obama - usa - 45
2 - ari - austarlia- 7
after running the function:
first table:
age - name
40 - Din
60 - George
second table:
id - name - country - age
1 - obama - usa - 45
I started the code (in the Picture attached
there)

This problem can be broken down into the following steps:
1. Find all the table names.
2. Loop through each table and delete the row which has age less than 20.
I added the following code, however you might need to customise it based on your requirements.
public class UpdateDB {
public static void main(String[] args) {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:C:/Users/Andrei/test.db");
String sql = "SELECT * FROM sqlite_master WHERE type='table'";
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
List<String> tableNames = new ArrayList<>();
// loop through the result set
while (rs.next()) {
tableNames.add(rs.getString(3));
}
System.out.println("BEFORE UPDATE");
System.out.println("---------------------------");
for (String table: tableNames) {
String sqlUpdate = "SELECT * FROM " + table + " ";
ResultSet rs2 = stmt.executeQuery(sqlUpdate);
while(rs2.next()) {
System.out.println(rs2.getInt("ID") + " " + rs2.getString("AGE"));
}
}
// This is the statement which deletes the rows
for (String table: tableNames) {
String sqlUpdate = "DELETE FROM " + table + " WHERE AGE < 20";
stmt.executeUpdate(sqlUpdate);
}
System.out.println();
System.out.println("AFTER UPDATE");
System.out.println("---------------------------");
for (String table: tableNames) {
String sqlUpdate = "SELECT * FROM " + table + " ";
ResultSet rs2 = stmt.executeQuery(sqlUpdate);
while(rs2.next()) {
System.out.println(rs2.getInt("ID") + " " + rs2.getString("AGE"));
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(UpdateDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

How to retrieve a single value?

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);

How can I print the column names from 3 tables joining JDBC? [duplicate]

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 3 years ago.
I have a 3 tables I have joined this query executes and prints out the tables data.
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected");
Statement st = conn.createStatement();
String query = "SELECT s.*, sup.name as supplierName , p.name as partName "+
"FROM supplies s "+
"INNER JOIN supplier sup on s.supplierNum = sup.supplierNum "+
"INNER JOIN parts p on s.partNum = p.partNum";
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("partNum"));
System.out.println(rs.getString("quantity"));
System.out.println(rs.getString("supplierName"));
System.out.println(rs.getString("partName"));
space();
}
} catch(Exception ex) {
System.out.println(ex);
}
But I was trying to add the column names so instead of the console printing:
It would to print the column names cascaded
supplierNum: S1
partNum: P1
quantity: 300
name: Smith
part: Nut
As suggested in https://stackoverflow.com/a/696794/11226302
You need to get the ResultSet meta data to programmatically get your column names from db.
Else, you can manually enter the names as suggested in other answers.
while(rs.next()) {
System.out.println("Supplier Name " + rs.getString("supplierNum"));
System.out.println("Part Name "+rs.getString("partNum"));
System.out.println("Quantity "+ rs.getString("quantity"));
System.out.println("SupplierName "+rs.getString("supplierName"));
System.out.println("PartName "+rs.getString("partName"));
space();
}
You can of course hard-code the column names because you already know them.
If you want to get them programmatically, then use the ResultSetMetaData similar to this:
Connection connection = ...
try (PreparedStatement ps = connection.prepareStatement(QUERY)) {
ResultSet resultSet = ps.executeQuery();
// get the meta data from the result set
ResultSetMetaData rsMeta = resultSet.getMetaData();
// receive the column count
int columnCount = rsMeta.getColumnCount();
// iterate them (their indexes start at 1, I think)
for (int i = 1; i < columnCount + 1; i++) {
// and print the column name, the type and the type name
System.out.println(rsMeta.getColumnName(i)
+ " ("
+ rsMeta.getColumnType(i)
+ ", "
+ rsMeta.getColumnTypeName(i)
+ ")");
}
} catch ...
...
}
If you want to directly output the column in your while loop, then get the meta data before that loop
ResultSetMetaData rsMeta = rs.getMetaData();
and then, inside the loop do
System.out.println(rsMeta.getColumnName(1) + ": " + rs.getString("supplierNum"));
System.out.println(rsMeta.getColumnName(2) + ": " + rs.getString("partNum"));
System.out.println(rsMeta.getColumnName(3) + ": " + rs.getString("quantity"));
System.out.println(rsMeta.getColumnName(4) + ": " + rs.getString("supplierName"));
System.out.println(rsMeta.getColumnName(5) + ": " + rs.getString("partName"));
From a resultSet you can optain his metadata
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
for (int i = 1; i <= cols; i++) {
String colName = meta.getColumnName(i);
System.out.printf("%s=%s\n", colName, rs.getString(i);
...
}

Java JDBC does not get generated keys without sequence columns

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

How do I delete a row from database table in Java

I am trying to develop a simple Java DVD library console app in Java. I have created a database table that contains a list of DVD's. I have managed to get the adding a new DVD to the database functionally working, but I am struggling to delete a row from the database. When I use a SQL statement to select a row (row 7) then run the line 'rs.delete' I get the following exception:-
Invalid cursor state - no current row.
Below is my database table:-
ID Film Name Genre Rating
-------------------------------
1 Robocop Sci-fi 18
2 Terminator Sci-fi 18
3 Alien Sci-fi 18
4 Big Fish Fantasy PG
5 The Pianist Drama 18
6 Total Recall Sci-fi 18
7 Carnage Comedy 18
Below is copy of my code. Please could somebody help?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dvdlibrary;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
*
* #author Andy
*/
public class DVDLibrary {
Connection con;
Statement stmt;
ResultSet rs;
String selection = "";
int id_num =0;
String film_name ="";
String genre ="";
String rating="";
public DVDLibrary()
{
DoConnect();
}
public void DoConnect() {
try
{
String host = "jdbc:derby://localhost:1527/DVDLibrary";
String username = "andyshort";
String password = "Pa55word";`enter code here`
con = DriverManager.getConnection(host, username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
/*
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
*/
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
public void GetUserInput()
{
System.out.println();
System.out.println("What would you like to do? Choose one of the following options.");
System.out.println("1. Display DVD library list");
System.out.println("2. Add a new film to database.");
System.out.println("3. Delete a film from the database.");
System.out.println();
Scanner user_option_selection = new Scanner(System.in);
selection = user_option_selection.next();
if(selection.equalsIgnoreCase("1"))
{
DisplayDVDList();
}
else if(selection.equalsIgnoreCase("2"))
{
AddRecord();
}
else if(selection.equalsIgnoreCase("3"))
{
DeleteRecord();
}
else
{
System.out.println("Incorrect option entered. Please try again.");
}
}
public void DisplayDVDList()
{
try
{
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void AddRecord()
{
Scanner new_film_details = new Scanner(System.in);
System.out.println("Please enter film name: ");
film_name = new_film_details.next();
System.out.println("Please enter film genre: ");
genre = new_film_details.next();
System.out.println("Please enter film rating: ");
rating = new_film_details.next();
try
{
rs.last();
id_num = rs.getRow();
id_num = id_num + 1;
rs.moveToInsertRow();
rs.updateInt("ID", id_num);
rs.updateString("FILM_NAME", film_name);
rs.updateString("GENRE", genre);
rs.updateString("RATING", rating);
rs.insertRow();
//stmt.close( );
//rs.close( );
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void DeleteRecord()
{
String id = "";
Scanner id_of_film_to_delete= new Scanner(System.in);
System.out.println("Enter ID of film you want to delete.");
id = id_of_film_to_delete.next();
int idInt = Integer.parseInt(id);
try
{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
rs = stmt.executeQuery(sql);
rs.deleteRow();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
}
use directly this query
"DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "+ idInt+");
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}
Use prepared statements to avoid SQL injection:
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM andyshort.dvds WHERE id = ?");
statement.setInt(1, idToDelete);
statement.executeUpdate();
You can directly use delete query if you have the Id before hand.
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
stmt.executeUpdate(sql);
But, it's better to use prepared statements instead of statements in order to avoid sql injection attacks.
String query= "DELETE FROM ANDYSHORT.DVDS WHERE ID = ? ";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1,idInt);
preparedStatement.executeUpdate();
You need to move the cursor to the first row before deleting the row, if you want to use deleteRow() method.
rs.first();
rs.deleteRow();

java-mysql program

i have a table - emp_details in mysql
i want to seatch an employ's id number in java.
if it is in the table , then show all the details of employee.
otherwise display an error message.
how i do this
Using JDBC
Here is an example You can build your solution from it.
Statement stmt = null;
String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");
System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
stmt.close();
}
ResultSet rs1=stmt.executeQuery("SELECT * FROM employee_details where Employee_ID='"+strEmpId+"'");
if(rs1.next()) {
System.out.println("Emp ID : " + rs1.getString(1));
System.out.println("Emp Name : " + rs1.getString(2));
System.out.println("Emp Salary : " + rs1.getString(3));
} else {
System.out.println("Emp ID not found");
}
If you want to know more about SQL just go through HERE

Categories

Resources