Got a question, how can i get 2 different variables from different tables using mysql? Is it possible to make it work from 1 query using prepared statement? I'm new at mysql database programming with java, so that's my problem.
I'm trying to get:
user_key from user table
project_key from project table
and yes, I know, table names should be in non singular form.
I'm trying :
String project_key = null;
String user_key = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://mysql:" + Config.getPortDB() + "/" + Config.getDatabase() + "?"
+ "user=" + Config.getUsername() + "&password=" + Config.getPassword());
String query ="SELECT user_key,project_key FROM user, project WHERE user_key = ? AND project_key = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
for(int i = 0; i < auths.size() ; i++ ) {
preparedStatement.setString(i+1, auths.get(i));
}
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()) {
project_key = rs.getString("project_key");
user_key = rs.getString("user_key");
}
System.out.println(project_key); // null
System.out.println(user_key); // null
What am I doing wrong here?
SELECT u.user_key,
p.project_key
FROM (select user_key from user WHERE user_key = ?) u,
(select project_key from project WHERE project_key = ?) p
If the tow tables has no relation at all you still can get the 2 values using subqueries
This is your current query:
SELECT user_key,project_key
FROM user, project
WHERE user_key = ?
AND project_key = ?
To get results from 2 tables use JOIN, like this:
SELECT u.user_key, p.project_key
FROM user u
JOIN project p ON p.userId = u.id
WHERE u.user_key = ?
AND p.project_key = ?
Related
I need to fetch the data from a table which multiple filters and limit rows from java script datatable request
SELECT coalesce(parent_id,siteid) as siteid, address, state, status, plan,
remarks, FROM archive LEFT OUTER JOIN site_mappings ON
site_dn = mrbts AND siteid = child_site_id
In my code i have a implementation to append the filter in the query before executing the prepared statement.
filters here is List<String[]> filters having values of filters with the column name (UPPER(mrbts) like UPPER('%6105%'))... 6105 is the filter string and mrbts is the column name
private String createFilterWhereClause(List<String[]> filters) {
StringBuilder sb = new StringBuilder();
Iterator<String[]> filterParmItr = filters.iterator();
while (filterParmItr.hasNext()) {
String[] filterParm = filterParmItr.next();
sb.append("(")
.append(filterParm[ScFilterCriteria.FILTER_PARM_VAL])
.append(")");
if (filterParmItr.hasNext()) {
sb.append(" and ");
}
}
return sb.toString();
}
During execution ,it forms the sql query as below and executed in prepared statement.
SELECT coalesce(parent_id,siteid) as siteid, address, state, status, plan,
remarks, FROM archive LEFT OUTER JOIN site_mappings ON site_dn = mrbts AND
siteid = child_site_id where UPPER(mrbts) like UPPER('%4105%') and
((UPPER(technology) like UPPER('%LTE%')))
It has an SQL injection vulnarability. In order to solve that , i am trying to secure it by use prepared statement set string as below,
SELECT coalesce(parent_id,siteid) as siteid, address, state, status, plan,
remarks, FROM archive LEFT OUTER JOIN site_mappings ON site_dn = mrbts AND
siteid = child_site_id where ?
Using prepared statement ,
PreparedStatement ps = null;
Connection connection = null;
ps = connection.prepareStatement(sql);
String filters = createFilterWhereClause(filterClause);
ps.setString(1, filters );
Problem here in the sql query formed with single quotes after set string ,
SELECT coalesce(parent_id,siteid) as siteid, address, state, status, plan,
remarks, FROM archive LEFT OUTER JOIN site_mappings ON site_dn = mrbts AND
siteid = child_site_id where '((UPPER(mrbts) like UPPER(\'%6105%\')))';
How to remove the single quotes during set string and or any other approach to do this ?
Could you someone help me.
The code for a static SQL statement would look like:
String query = "SELECT coalesce(parent_id,siteid) AS siteid, address, state, status, "
+ "plan, remarks "
+ "FROM archive "
+ "LEFT OUTER JOIN site_mappings ON site_dn = mrbts "
+ "AND siteid = child_site_id "
+ "WHERE UPPER(mrbts) LIKE UPPER(?) "
+ "AND UPPER(technology) LIKE UPPER(?)";
// UPPER probably is not needed; there was one spurious comma after "remarks"
String mrbts = "4105";
String technology = "LTE";
try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
preparedStatement.setString(1, "%" + mrbts + "%");
preparedStatement.setString(2, "%" + technology + "%");
try (resultSet = preparedStatement.executeQuery()) {
while (resultSet.next()) {
...
}
return list; // Or such
}
}
For a dynamic number of criteria:
StringBuilder sb = new StringBuilder();
List<Object> params = new LinkedList<>();
...
sb.append(" AND mrbts LIKE ? ");
params.add(mrbts);
...
int column = 1;
for (Object param : params) {
preparedStatement.setObject(column, param);
++column;
}
Change your query to :
SELECT coalesce(parent_id,siteid) as siteid, address, state, status, plan,
remarks, FROM archive LEFT OUTER JOIN site_mappings ON site_dn = mrbts AND
siteid = child_site_id where ((UPPER(mrbts) like UPPER(?));
Set only parameters with prepared statement parameters.
To add dynamic conditions :
//Your base sql statement
String sqlString = "Select ...";
//add condition only in few cases
if(mycondition){
sqlString += "WHERE mycondition = ?"
}
ps = connection.prepareStatement(sql);
//bind the corresponding dynamic parameter you just added in the where clause.
if(mycondition){
ps.setString(1, myparameter );
}
It is safe to do that if there isn't any user input concatened with the sqlString.
As Joop Eggen said, use prepared statements
I have looked through similar threads on this site and none of the suggested answers seem to work. I am writing a java program that interacts with an Access database using SQL. I have successfully connected to the database and pulled information from it. However, I need to update the database and I keep running into this error
UCAExc:::3.0.7 user lacks privilege or object not found: SLIPSET
Why am I not able to successfully update the Access database?
Here is the code relevant to the updates
String sqlSlip ="UPDATE Slip" +
"SET slipOpen = 0 AND boatID =?" +
"WHERE slipNumber = ?";
PreparedStatement slipUpdate = connection.prepareStatement(sqlSlip);
slipUpdate.setDouble(1, boatIDdub);
slipUpdate.setDouble(2, rs.getInt("slipNumber"));
ResultSet updateSlip = slipUpdate.executeQuery();
String sqlCustomer = " INSERT INTO Customer(customerLName, customerFName, slipNumber, boatID, customerNumber)" +
"VALUES (?, ?, ?, ?, ?)";
PreparedStatement custUpdate = connection.prepareStatement(sqlCustomer);
custUpdate.setString(1,custLName);
custUpdate.setString(2, custFName);
custUpdate.setDouble(3, rs.getInt("slipNumber"));
custUpdate.setDouble(4, boatIDdub);
custUpdate.setDouble(5, customerNumber);
ResultSet updateCust = custUpdate.executeQuery();
connection.close()
If you were to inspect the contents of your sqlSlip string you would see that it contains
UPDATE SlipSET slipOpen = 0 AND boatID =?WHERE slipNumber = ?
You need to add a space to the end of each string fragment and use a comma instead of AND ...
String sqlSlip ="UPDATE Slip " +
"SET slipOpen = 0, boatID = ? " +
"WHERE slipNumber = ?";
... so that the string contains
UPDATE Slip SET slipOpen = 0, boatID = ? WHERE slipNumber = ?
Also note that to perform an INSERT query you need to use .executeUpdate(), not .executeQuery().
Hi this my java code here am using hibernate to check whether this email id and password exist in db or not could anybody plz exp line me how to place the value to this place holders.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).list();
ses.close();
Thanks in advance
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo rp where rp.email = :emailAddress and rp.pwd = :password";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("emailAddress", Your email address)
.setParameter("password", Your password)
.list();
ses.close();
You should use a prepared statement instead of a string. example here
PreparedStatement preparedStatement = con.prepareStatement ("from RegisterPojo where email=? and pwd=?");
preparedStatement.setString(1, "email");
preparedStatement.setString(2, "password");
You have to modify your query like this,
query = "from RegisterPojo where email =:email and pwd =:password ";
List<RegisterPojo> list = ses.createQuery(query)
.setParameter("email",emailVal)
.setParameter("password",emailVal)
.list();
Read the hql docs here
Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
ses.close();
Try this one.
Session ses = HibernateUtil.getSessionFactory().openSession();
String query = "from RegisterPojo where email = '" + varEmailAddress + "' and pwd = '" + varPassword + "'";
List<RegisterPojo> list = ses.createQuery(query).list();
ses.close();
Sorry This Is not Answer but instead another case, in above case #Grigoriev Nick suggested
query = "from RegisterPojo where email=? and pwd=? ";
List<RegBean> list = ses.createQuery(query).setParameter(0,emailVal).setParameter(1,emailVal).list();
but here the script starts with directly from clause while what if I want want to used sql like below
WITH A (
/// do some selection from many tables using various union as per my requirement
),
B (
/// another set of sqls for different set of data
)
select XXX from A a join B b on a.XYZ = b.xyz
where
/// few more fixed where clause conditions
AND A.SOME_COLUMN = ? // Here Instead Of String Concatenation I want to
//use Query parameters but using hibernate instead of raw Prepares statements
I try to create a PreparedStatement:
stmt = conn.prepareStatement("SELECT POLBRP, POLTYP, POLNOP, INCPTP, TRMTHP, " +
"CLTKYP , CANDTP, POLSTP, EXPRYP, OINCPP, CANRNP, PAYMDP,
KCNFLP, KCRTSP, KACADP, KSCHMP, EXPRYP FROM "
+ POLHDR + " WHERE POLNOP = " + idNumber +
" AND POLBRP = " + branch + " AND POLTYP = " + product +
" AND OINCPP <= "+date );
And this throws an SQLException: [SQL0206] Column AD not in specified tables.
I have no idea where it's getting column AD from as I never specified it in the select clause (unless I'm being completely blind and stupid)
Can anyone help?
If your variables are strings, e.g. branch
" AND POLBRP = " + branch + " ...
then you forgot to quote the values
" AND POLBRP = '" + branch + "' ...
but the real solution is using placeholders
... AND POLBRP = ? ...
which would prevent such problems once and for all, this is what PreparedStatement is designed for
Try to change your query into this:
SELECT
POLBRP,
POLTYP,
POLNOP,
INCPTP,
TRMTHP,
CLTKYP,
CANDTP,
POLSTP,
EXPRYP,
OINCPP,
CANRNP,
PAYMDP,
KCNFLP,
KCRTSP,
KACADP,
KSCHMP,
EXPRYP
FROM TableName WHERE POLNOP = ? AND POLBRP = ? AND POLTYP = ? AND OINCPP <= ?";
Then use:
stmt.setString(1, "ValueOfPOLNOP");
...
When your query is being executed ? will be replaced with the value you passed into PreparedStatement#setString(int, String) method
Preventing SQL Injection in Java shows the proper use of PreparedStatement:
Prepared Statements Variables passed as arguments to prepared
statements will automatically be escaped by the JDBC driver.
Example: ps.1
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
From the same source, following in the same section:
Although Prepared Statements helps in defending against SQL Injection,
there are possibilities of SQL Injection attacks through inappropriate
usage of Prepared Statements. The example below explains such a
scenario where the input variables are passed directly into the
Prepared Statement and thereby paving way for SQL Injection attacks.
Example: ps.2
String strUserName = request.getParameter("Txt_UserName");
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");
i have this java code:
ArrayList<MessageMap> ids = getNewMail(UserID, type, maxIdMessage);
Message[] message = new Message[ids.size()];
if(ids.size()>0){
ResultSet rs;
int j =0;
for(MappaMessaggi i : ids){
pstmt = conn.prepareStatement("SELECT * FROM Messaggi WHERE MessageID = ?");
pstmt.setInt(1, i.getMessageID());
rs = pstmt.executeQuery();
rs.next();
.
.
.
}
where getNewMail is:
public synchronized ArrayList<MessageMap> getNewMail(int UserID,int type,int max){
ArrayList<MessageMap> map = new ArrayList<MessageMap>();
try {
pstmt = conn.prepareStatement("SELECT * FROM MessageMap WHERE UserID = ? AND TipoID = ? AND MessageID > ?");
.
.//fill arraylist with resultSet
.
}
I know that is possible to do the same with just one query but i don't know how.. can someone open my eyes? :) thanks!!!
EDIT: i try:
SELECT i.*
FROM Messaggi AS i
INNER JOIN MessageMap AS p i.MessageID = p.MessageID
WHERE p.MessageID = 1 AND p.UserID = 1 AND p.TipoID = 2
BUT I RETRIEVE:
#1064 - 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 'i.MessageID = p.MessageID WHERE p.MessageID = 1 AND p.UserID = 1 AND p.TipoID = ' at line 3
Try this:
SELECT i.*, p.*
FROM Messaggi i
INNER JOIN MessageMap p ON i.MessageID = p.MessageID
WHERE i.MessageID = ? AND p.UserID = ? AND p.TipoID = ?
Based in your question and queries, the simple solution I find could be this query (maybe there are another columns that relate your tables)
SELECT A.*
FROM MessageMap A
INNER JOIN Message B on A.MessageId = B.MessageId
WHERE
A.UserId = ?
AND A.TipoID = ?
AND A.MessageId = ?
Also, please specify if you need those 3 parameters or you could not send any of them.