Trying to get all the data in the row with the specified name string. Im getting a syntax error right now. myConn is declared in the constructor and name is a varchar in the database named organization. My error code is "Can not issue executeUpdate() or executeLargeUpdate() for SELECTs"
public void getOrgByName(String name){
try {
st = myConn.createStatement();
String query = "SELECT * FROM organization WHERE name = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, name);
preparedStmt.executeUpdate();
}catch(Exception e){
System.out.println("Cannot get org name" + e);
}
}
You’re performing a select query so you’ll need to use executeQuery i.e
Replace this:
preparedStmt.executeUpdate();
With this:
ResultSet rs = preparedStmt.executeQuery();
Related
I'm trying to execute a LIKE query in Java using prepared statements but I'm getting the following error
ORA-00904: "%12P1A%": invalid identifier
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DataSourceFactory.getConnection();
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, "%12P1A%");
resultSet = statement.executeQuery();
//....
}catch (SQLException e) {
throw new DAOException(e.getMessage());
} finally {
DaoUtil.closeAll(connection, statement, resultSet);
}
May I know why is this incorrect?
For further Information, I'm actually getting '%12P1A%' by some other function so the code is something like
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, getValue());
the query parses to something like
select * from users where userID like '%12P1A%'
but it is throwing MISSING IN or OUT Paramter. Idk why it is not picking the value. Any suggestions?
You could extract the value between '% and %' that you are getting from the input and then create your query as -
statement = connection.prepareStatement("select * from users where userID like '%" + <value-from-some-other-method> + "%'");
If there is an option, ask the method response to be the value directly instead of having it formatted for query parameter.
In my Struts2 Java web application users are allowed to query the database. As an example, the user needs to get the employee details whose first name is equal to 'Charles'. Then s/he can select the report columns and criteria (firstname='Charles').
Once the user gives above inputs it need to save the relevant SQL query into the database.
e.g. SQL -> SELECT * FROM employee WHERE firstname='Charles'
Here is what I am trying in my action class.
try {
connection = DriverManager.getConnection(
SelectAction.getDatabase(), SelectAction.getUser(),
SelectAction.getPassword());
if (connection != null) {
System.out.println("Database connection established!");
stmt = connection.createStatement();
String sql = "INSERT INTO reports (report_id, sql) values ('" + reportId + "', '" + sqlQ + "');";
System.out.println("sql--->" + sql);
// Executing query
stmt.executeQuery(sql);
return SUCCESS;
} else {
System.out.println("----Failed to make connection!");
return ERROR;
}
} catch (SQLException e) {
System.out.println("Connection Failed!!");
e.printStackTrace();
return SUCCESS;
}
This is my insert query.
INSERT INTO reports (report_id, sql) values ('mynewreport', 'SELECT * FROM employee WHERE firstname='Charles'');
I am getting following error in my console.
ERROR: syntax error at or near "Charles"
I think here I am using a String so that the problem is with quotes('). I am using postgreSQL as database.
Any suggestions to solve this issue ?
Never use string concatenation of user supplied values to build a SQL statement.
Never use string concatenation of any non-integer values to build a SQL statement.
You will leave yourself open to SQL Injection attacks and/or SQL statement errors.
Hackers will love you for allowing them to steal all your data, and the nefarious ones will corrupt or delete all your data, while laughing maniacally at you on their way to the bank.
Use PreparedStatement and parameter markers.
String sql = "INSERT INTO reports (report_id, sql) values (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, reportId);
stmt.setString(2, sqlQ);
stmt.executeUpdate();
}
I'm not able to execute the query here.It says the above mentioned error.I have tried with 'Select * from customer' query and it is working.I can't figure out where am i going wrong.Please help and thanks in advance.
The full query is- SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE FIRST_NAME='SHIVAM';
The error message is- com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErr orException: Unknown coloumn 'SHIVAM' in 'where clause'
DefaultTableModel model;
model=(DefaultTableModel)tblSearchCustomer.getModel();
try{
Class.forName("java.sql.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/divign","root","password");
Statement stmt=con.createStatement();
String sfld=(String) searchfldCB.getSelectedItem();
//this stands for Search Field(ComboBox)
String op=(String) opCB.getSelectedItem();
//this stands for operator(ComboBox)
String crit=criteriaTF.getText();
//this stands for criteria
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld+""+op+""+crit+" ;";
//This Query is not Executing
ResultSet rs=stmt.executeQuery(query);
while(rs.next()) {
model.addRow (new Object[ ] {
rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getInt(5),
rs.getString(6),rs.getInt(7)
} );
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e.toString());
}
When you generate your query, there are no single quotes in your where statement, which means you'll get WHERE FIRST_NAME=SHIVAM, so it tries to compare first_name to a column called SHIVAM which doesn't exist
So here is the corrected query-
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,PASSWORD,ADDRESS,COUNTRY,AGE,GENDER,EMAIL_ADDRESS,PHONE_NUMBER FROM CUSTOMER WHERE " +sfld+" "+op+" '"+crit+"' ;";
Notice the inverted commas around crit....now if i type SHIVAM in jTextField (criteriaTF) the name will be executed in MySQL with inverted commas i.e. 'SHIVAM'
String query="SELECT CUSTOMER_ID,FIRST_NAME,LAST_NAME,COUNTRY,AGE,GENDER,EMAIL_ADDRESS FROM CUSTOMER WHERE" + sfld+""+op+""+crit+" ;";
In the where condition you haven't mentioned the column name to assign the value of sfld+""+op+""+crit.
You have to provide the column name next to where clause.
I am implementing a search method, i want to search a data in a Jtable ( wich contains 2 columns id and name) based in id and name both. Till now I can search using just one of, id or name but cannot do that using them both. I tried a solution, but it is not working it just search for the last one ( id or name). For example if i start with try and catch by name and then id, it only goes with id search. And if I start with id and the name, it searches just by name. Can u help me please.
The code :
`private void textField1KeyReleased(java.awt.event.KeyEvent evt) {
PreparedStatement pst=null;
ResultSet rs=null;
if (textField1.getText().length() > 0){
try{
String sql = "select * from compte_utilisateur where nom=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
**catch(Exception e){JOptionPane.showMessageDialog(null, e);}
try{
String sql = "select * from compte_utilisateur where id_utilisateur=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
else update_table();
}`**
Use just one SQL call passing the same value from the field twice
select * from compte_utilisateur where nom=? or id_utilisateur=?
You should to add jar/folder this rs2xml.jar in your project
String sql="Select * From Inventarizimi where Regjistrimi=?";
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con= (Connection) DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","Inventarizimi"); PreparedStatement preStatement = con.prepareStatement(sql); preStatement.setString(1, txtRegjistrimi.getText());
ResultSet result = preStatement.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(result));
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.