unrecognized problem in java using oracle - java

b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
user=tf1.getText();
pass=new String(tf2.getPassword());
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","jashan","noor1032");
PreparedStatement stmt=con.prepareStatement("select * from jashan.student where 'name1'=? and 'password'=?");
stmt.setString(1, user);
stmt.setString(2, pass);
ResultSet Rs=stmt.executeQuery();
if(Rs.next())
{
JOptionPane.showMessageDialog(f, "success!!");
}
else
{
JOptionPane.showMessageDialog(null, "incorrect username/password","warning",JOptionPane.WARNING_MESSAGE);
}
}
catch(Exception f)
{
System.out.println(f);
}
}
actually, i want that the code matches the username and password, but it is not doing so...whenever i execute, it shows invalid password/username....i don't know why....i have a table in oracle 11g which has columns student_id, name1,gender,address, email_id, phone_number,and password in the same order as defined. can anyone tell me what is the problem??

You have given single qoute around your column name that is causing the issue. Remove that and it should work
Change 'name1' to name1 and 'password' to password in your query

You have managed to create a table with lowercase column names. As you have experienced, it causes trouble as Oracle converts all names (for tables, columns etc.) to upper-case by default.
You have two options:
Drop the table and recreate it with uppercase names.
Use double quotes around the columns names to prevent Oracle from converting them to uppercase:
select * from jashan.student where "name1"=? and "password"=?
Or when you put it in Java:
PreparedStatement stmt = con.prepareStatement("select * from jashan.student where \"name1\"=? and \"password\"=?");
In any case, single quotes around column names is incorrect.

Related

How to fix 'terminated' while using rs.getString

When trying to pull from an SQL database, I get in Java console.
I am able to enter my ID manually in the prepareStatement, but I can't use setString to work with with the prepareStatement.
I haven't throught of too much to try, but I did find that the issue is within the while statement. rs.next returns false when it should return true. The information in SQL has been committed, and I can call all of the information in java using a function that reads out the entire table.
getemployeeDataById("01");
private static void getemployeeDataById(String e_id) {
DBConnection dbConnection = DBConnection.getInstance();
PreparedStatement ps;
try {
ps = dbConnection.getConnection().prepareStatement("select * from employee where E_ID = ?");
ps.setString(1, e_id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("ename"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
SQL
CREATE TABLE EMPLOYEE
(E_ID CHAR(3) PRIMARY KEY,
ENAME CHAR(25),
DOB CHAR(25),
EMAIL CHAR(25),
PHONE CHAR(25),
ADDRESS CHAR(25));
INSERT INTO EMPLOYEE
VALUES
('01','JEREMY MANN','12/23/1992','jeremy#jeremy.com','317-528-1234','123 CandyCane Lane');
I am expecting to get the name outputted in the console, so for this example it would be "JEREMY MANN." The code runs and then in the Eclipse Java console it shows Application [Java Application]. It runs into an issue within the while statement, but I'm not sure what's causing rs.next to be false.
In Oracle 11g (well, Oracle versions generally) CHAR is a fixed width type, and if you give it a value shorter than the given width, it will be padded with blanks (which might not be obvious if you just dumped the table contents). In this case, your key is length 3, but the string "01" is length 2, so that won't work.
Try VARCHAR2 for the column types, that's a variable length string.

invalid column index error in java while fetching data from oracle 10g database. Cant figure out whats wrong

Code snippet:
On a button click, actionevent will be called
public void actionPerformed(ActionEvent e)
{
Function f = new Function();
Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.
ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.
rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
Here is the code snippet for nested class Function which is inside the main class:
class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
Please help figure out the problem.
Don't put the parameter placeholder ? in single quotes.
This:
ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
should be
ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
The ? is not recognized as a placeholder if you enclose it in single quotes.
Sorting out the bind variable will fix your immediate issue.
You should explicitly specify what columns you want selected and that way you'll only get what you need (someone might add a BLOB column later) and you'll get them in the right order (someone might change the table create script before running on another DB instance, although you are looking up the columns by name, a different order would only impact if you were using positional indexes).
Ditto on the other answer re: bind variables (i.e. no quotes)
Plus, "select * from" is never a good idea, ask your DBA.
Obviously your code is for example, but you should make sure you free up any resources (Connection, Statement, ResultSet) as soon as they are done with. Use Java 7 try-with-resources.

Read a string with apostrophe from a JTextField and save it on a database

I have many JTextField objects and I want to read, in one of them, a string that contains apostrophes and then, this It will be saved on a database. The problem is when I try to save this string, because I obtain this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'k')' at line 1
I put the apostrophe in a JTextField and the "k" letter is in the next JTextField. I can't understand if who can't read this kind of character is the database (I have a database written in SQL and I use MySQL), or the JTextField object. What can I do?
This is the code that save the strings caught from the JTextField objects (I get the strings into another method, simply using the method jTextField.getText();):
public void setNuovaAzienda(){
try {
int contCliente = 0;
Class.forName(NOMEDRIVER); //avvio il driver
conn = DriverManager.getConnection(SERVERURL, USER, PASSWORD);
Statement st = conn.createStatement();
Statement st1 = conn.createStatement();
Statement st2 = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(IdCliente) FROM cliente");
while (rs.next())
contCliente = rs.getInt(1);
contCliente++;
int showConfirmDialog = JOptionPane.showConfirmDialog(null,"Vuoi confermare l'inserimento del nuovo cliente?", "Conferma Inserimento", JOptionPane.YES_NO_OPTION);
if (showConfirmDialog == 0) {
try {
st1.executeUpdate("INSERT INTO cliente () VALUES ('"+contCliente+"', '"+citta+"', '"+indirizzo+"', '"+nCivico+"', '"+telefono+"')");
st2.executeUpdate("INSERT INTO personagiuridica () VALUES ('"+contCliente+"', '"+partitaIva+"', '"+nomeAzienda+"', '"+ragSociale+"', '"+fax+"')");
ImageIcon icon = new ImageIcon("C:\\Users\\salva\\Documents\\NetBeansProjects\\JavaApplication10\\src\\javaapplication7\\Icons\\icona v.png");
JOptionPane.showMessageDialog(null, "Cliente Inserito", "Conferma Inserimento", JOptionPane.INFORMATION_MESSAGE, icon);
InserisciOrdine linkInserisciOrdine;
linkInserisciOrdine = new InserisciOrdine();
linkInserisciOrdine.setLocationRelativeTo(null);
linkInserisciOrdine.setVisible(true);
dispose();
} catch (SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
conn.close();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
contCliente, citta, indirizzo, etc. are global variable.
Sounds like you construct your SQL statements as a String, embedding the data directly, like
String dataString = ...; //get value from field
String sql = "INSERT INTO `mytable` (`col`) VALUES ('"+dataString+"')";
This is wrong, since if you have single quote in your string, this will result in invalid statement. Try outputting that string to System.out and executing it in the SQL worksheet, you should see what goes wrong. You should use Prepared Statements instead:
//Assuming you have jdbc Connection named conn
String dataString = ...; //get value from field
PreparedStatement ps = conn.prepareStatement("INSERT INTO `mytable` (`col`) VALUES (?)");
ps.setString(1, dataString);
ps.execute();
ps.close();
It will give you a decent protection against SQL injections as a bonus.
If you are unable to rewrite your code with prepared statements (e.g. legacy third-party API), then you should escape single quotes in your string, by replacing them with two single quotes (' -> '').
UPDATE
Indeed you do construct the statements using concatenation. AVOID THIS, unless you want to get hacked by a random script kiddie one day. Read about SQL injections, there's plenty of info, and they are one of the main vectors of hacker attacks.

Sqlite error (missing database) while trying to update jtable

private void checkKeyPressed(java.awt.event.KeyEvent evt) {
try{
String ch ="select * from check where name like ?%";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText());
ResultSet rs=pst.executeQuery();
checker.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
above is the code im using, and im getting a:
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (near "check": syntax error)
i have a table named check in sqlite, and im trying to create a search engine in my jframe, so when i enter text in a textfield the jtable filters automatically. any idea why this error could come about.
You have to change this part, if you need to pass % you have to pass it with set Method and as check is a reserved keyword in sqlite change it to check
String ch ="select * from check where name like ?%";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText());
with
String ch ="select * from `check` where name like ?";
PreparedStatement pst=conn.prepareStatement(ch);
pst.setString(1, check.getText()+"%");

Oracle Java SQL Exception Error: ORA-0094

I am trying to write a function for this button. I want to be able to pass it a textfield value and be able to go into my database to retrieve some information.....
Can somebody explain to me what is going on and provide me a solution to this madness?
Thank you all xD
I keep running into this stupid problem:
ACTION1 createdoracle.jdbc.driver.T4CConnection#484845aa
Exception:java.sql.SQLSyntaxErrorException: ORA-00904: "ART": invalid identifier
Code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CLASS TYPE
//LIST ALL OFFERED CLASSES AND REVENUE
try{
String classtype = jTextField1.getText().trim();
if(classtype.equals("")){
JOptionPane.showMessageDialog(this, "Sorry Wrong input.... Please try again....");
}
else if(classtype != ""){
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection(
"jdbc:oracle:thin:#fourier.cs.iit.edu:1521:orcl",
"usr","pwd");
Statement stmt = conn.createStatement();
System.out.println("ACTION1 created"+conn+"\n\n");
String ct = jTextField1.getText().trim();
//String aa = "SELECT * FROM CLASS WHERE TYPE="+classtype;
//System.out.println(aa);
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE="+ct);
while (rset.next()) {
System.out.println(rset.getString("TITLE") + " ");
}
JOptionPane.showMessageDialog(this, "Class Type: "+classtype);
stmt.close();
conn.close();
System.out.println("Connection Closed");
}
catch(Exception sqle){
System.out.println("\nException:"+sqle);
}
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, "Please Retry input....", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Let me guess ... does the ct String start with "ART" (or some variation)?
If so, the problem is that SQL requires quotes around string literals. Your query probably looks to Oracle something like this:
SELECT * FROM CLASS WHERE TYPE=Art of War
but it should look like
SELECT * FROM CLASS WHERE TYPE='Art of War'
There are two ways to fix this:
Assemble the query with quote characters around ct.
Write the query as "SELECT * FROM CLASS WHERE TYPE=?", use a PreparedStatement instead of a Statement and use the setString method to supply the parameter value.
If done properly, the second approach is both more secure and more efficient. (The problem with string-bashing the query and using Statement is that you are potentially making yourself vulnerable to SQL injection attacks.)
You're passing the value as part of the query, and the string concatenation you're doing makes the SQL into:
SELECT * FROM CLASS WHERE TYPE=ART
(where ART is the value of ct from the textfield) so it's trying to find a column on the table called ART. At an absolute minimum you need to quote the string:
ResultSet rset = stmt.executeQuery("SELECT * FROM CLASS WHERE TYPE='" + ct + "'");
But really don't do this; as #Andreas_D says you're leaving yourself open to SQL injection. Always use prepared statements and bind variables:
String sql = "SELECT * FROM CLASS WHERE TYPE=?";
PrepareStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, ct);
ResultSet rset = stmt.executeQuery();

Categories

Resources