count_teachers(dept_name VARCHAR): return as an OUT parameter the total number of teachers belonging to the department named exactly as dept_name.
I can't do this last part of the exercise, I need to do this procedure in Java. I don't know how to do this subquery because it is inside a procedure with in and out parameters
public static void count_Teacher_By_Department_Procedure() {
try {
Connection con = conexion("jdbc:hsqldb:.\\database\\db");
Statement stt;
stt = con.createStatement();
String sql = "DROP PROCEDURE count_Teacher_By_Department_Procedure IF EXISTS;";
stt.executeUpdate(sql);
sql = "CREATE PROCEDURE count_Teacher_By_Department_Procedure(IN id int, OUT nombre Varchar(20))"
+ "READS sql DATA "
+ "BEGIN ATOMIC "
+ "SET id = SELECT COUNT id FROM teachers WHERE dept_num IN (SELECT dept_num FROM departments WHERE name = nombre); " // pasar al set el parametro out
+ "END";
stt.executeUpdate(sql);
con.close();
} //
catch (SQLException ex) {
Logger.getLogger(Act3_4.class.getName()).log(Level.SEVERE, null, ex);
}
}
It seems you have some syntax error and your IN and OUT parameters are not correct.
sql = "CREATE PROCEDURE count_Teacher_By_Department_Procedure(OUT idcount int, IN nombre Varchar(20))"
+ "READS sql DATA "
+ "BEGIN ATOMIC "
+ "SET idcount = SELECT COUNT( id ) FROM teachers WHERE dept_num IN (SELECT dept_num FROM departments WHERE name = nombre); " // pasar al set el parametro out
+ "END";
Related
This is my entire code:
import java.sql.*;
import java.io.*;
public class VerInformacaoPassageiro {
public static void main(String args[]) {
String dbname = "BD22";
String dbuser = "postgres";
String password = "12345";
String url = "jdbc:postgresql://localhost:5432/" + dbname;
try {
BufferedReader in;
in = new BufferedReader( new InputStreamReader( System.in ));
System.out.print("Numero de identificacao: ");
String identificacao = in.readLine();
Connection c = DriverManager.getConnection(url, dbuser, password);
c.setAutoCommit(false);
Statement stmt = c.createStatement();
String query = "SELECT nomeP, sexo, destinopretendido, dataviagem " +
"FROM passageiros " +
"WHERE nidentificacao='" + identificacao + "';";
System.out.println("QUERY: " + query);
ResultSet rs = stmt.executeQuery(query);
System.out.println( "Informacao do passageiro com numero de identificacao " + identificacao);
System.out.println( "---------------------------------------");
while ( rs.next() ) {
int nidentificacaoP = rs.getInt("nidentificacao");
String nome = rs.getString("nomeP");
String sexo = rs.getString("sexo");
String destinopretendido = rs.getString("destinopretendido");
String dataviagem = rs.getString("dataviagem");
if (nidentificacaoP == NULL)
System.out.print("Identificacao nao encontrada");
else
System.out.println( nome + " do sexo " + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
}
rs.close();
stmt.close();
c.close();
}
catch (Exception e) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
}
}
But my doubt is in this part of the code:
if (nidentificacaoP == NULL)
System.out.print("Identificacao nao encontrada");
else
System.out.println( nome + " do sexo " + sexo + " para o destino " + destinopretendido + " no dia " + dataviagem );
}
rs.close();
stmt.close();
c.close();
My goal is to find a certain ID number in a database that will give me a passenger's information. If this ID is not in the database I want to use an if to write "ID not found" but I don't know how to do this. (I left it as NULL inside the if because I didn't know what to put in it so it won't be empty, so I can submit it here on Stack Overflow). What should I write inside the if to check if the ID exists?
There are at least 3 errors/misconceptions in this code.
SQL injection
String query = "SELECT nomeP, sexo, destinopretendido, dataviagem " +
"FROM passageiros " +
"WHERE nidentificacao='" + identificacao + "';";
Imagine the user types this on the command line:
Whatever' OR 1 == 1; EXEC 'FORMAT C: /Y'; --
That would mean the query matches many records (OR 1 == 1 means it matches all of them), and it'll format your drive. This is called SQL injection; to avoid it, use PreparedStatement and NEVER put user input directly into the SQL. In general your SQL statements should be string literals.
Selecting columns vs retrieving them
String query = "SELECT nomeP, sexo, destinopretendido, dataviagem " +
....
rs.getInt("nidentificacao")
Your select statement states that you want 4 values to be returned for each matching row in the query. You then ask for the value of row 'nidentificacao' which isn't in there. The only 4 string values valid in rs.getInt, are nomeP, sexo, destinopretendido and dataviagem, because those are the only 4 columns in the query.
Misunderstanding of how 'not found' is registered
Your query returns a number of rows. while (rs.next()) loops once for each row. If nidentificacao is unique, given that you are looking for a specific value of it, your query returns either 1 row, or 0 rows.
If no row with nidentificacao at the searched-for value exists, you would get no rows. In your code, you assume you get a row, with null as value for rs.getInt("nidentificacao"); which isn't how it works.
NULL misconception
In SQL, NULL is a thing. In java, there's, at best, null (case sensitive). The various .getX() methods tend to return a placeholder value and not null for SQL NULL values. For example, if your SQL query returns NULL and you call rs.getInt(column) to retrieve it, you get 0, not null - that's because in java primitives cannot be null.
It isn't relevant here (checking for SQL NULL is not how you determine that no results are found; you determine that by realizing rs.next() will return false always - even the first time you call it) - but if it had been, that's not how its done.
Assuming identificacao is a unique identifier, the query will return either one or no rows, so you don't need to process the result set with a while, but with an if:
// Single row found
if (rs.next()) {
int nidentificacaoP = rs.getInt("nidentificacao");
String nome = rs.getString("nomeP");
String sexo = rs.getString("sexo");
String destinopretendido = rs.getString("destinopretendido");
String dataviagem = rs.getString("dataviagem");
System.out.println
(nome + " do sexo " + sexo + " para o destino " +
destinopretendido + " no dia " + dataviagem);
// No row found
} else {
System.out.print("Identificacao nao encontrada");
}
Mandatory side note:
Concatenating the condition like that is at best a bad practice and at worst leaves your application vulnerable to SQL Injection attacks if identificacao is received from user-controlled input. You should probably convert this query to a PreparedStatemet with placeholders.
I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}
3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.
I have all table names in a drop down list in a java application.
I want display the number of records in a table on JLabel.
but I'm getting the following error
java.sql.SQLSyntaxErrorException: ORA-00903: invalid table name
I have tried this:
try {
String tableName = LoginFrame.userName + "." + this.ddlTableName.getSelectedItem().toString();
JOptionPane.showMessageDialog(null, tableName);
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from '" + tableName + "'");
rs = pst.executeQuery();
while (rs.next()) {
this.lblRecordStat.setText(rs.getString("num"));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
System.out.println(ex);
}
In Oracle, quotes ('s) are used to denote string literals. Object names (such as tables) should not be surrounded by them. Lose the quotes and you should be OK:
pst = (OraclePreparedStatement) con.prepareStatement
("select count(*) as num from " + tableName);
You are passing string as table name. Table names in Oracle can be either inside `` qoutes or without any quotes.
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from " + tableName );
or
pst = (OraclePreparedStatement) con.prepareStatement("select count(*) as num from `" + tableName + "`");
I have created a database and a set of table using JDBC and SQLite in Eclipse.
I am trying to update the table using the following code:
public static void update()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM CUSTOMERS;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully");
}
As far as I can understand the SQL syntax I m using says:
update the table customers2 and set the address as Byron where phone =2
But am getting the following error:
java.sql.SQLException: no such column: Byron
Which tells me it is interpreting my request as asking to alter the column named Byron, which is not what I believe the code to be saying?
As per SQL syntax, varchar values should be used with single quotes so update this:
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
to
String sql = "UPDATE CUSTOMERS2 set ADDRESS = 'Byron' WHERE PHONE=2;";
If you don't use the single quotes, SQL assumes that you are trying to set the value using a different column and hence it throws the error:
java.sql.SQLException: no such column: Byron
ADVICE: Use PreparedStatment for dynamic parameter queries
PreparedStatement stmt;
String sql = "UPDATE CUSTOMERS2 set ADDRESS=? WHERE PHONE=?";
stmt = c.prepareStatement(sql);
stmt.setString(1, "Byron");
stmt.setInt(2, 2);
stmt.executeUpdate();
I am using hadoop-1.0.4 and hive-0.10.0 in redhat5. Service start successfully. I am able to create, drop, select table easily but I don't know how to insert data.
For example I have two text box and on button click I want to store data in table (userInfo). I have no clue how to store textbox vaue in userInfo(id,password).
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/enggheads","", "");
Statement stmt = con.createStatement();
String tableName = "testHiveDriverTable";
stmt.executeQuery("drop table " + tableName);
ResultSet res = stmt.executeQuery("create table " + tableName + " (key int, value string)");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
}
It's Java, but I don't know how to insert two field value because Hive insertion is different than MySQL or other database syntax.
Create a dummy table in hive like below
create table dummy(dummy string) location '/path';
Above path will have a file which contains data X
Now run insert query from jdbc driver like below.
insert into table tblname select forntendvalue1,frontendvalue2 from dual;