Retrieve data from database by java & myphpadmin - java

The user will be asked to enter one E_Id (PK) to retrieve the "salary" data of that employee. For example, the user key in e.g. 105, it will return the data which is 2600. What is the query I should write as the user will enter the different PK each time to get different data? I have connected successfully to the myth-admin.
SELECT salary FROM Employee WHERE E_ID = ?????? (supposed to be the input of user)
Thanks in advance

The simpliest way to do this is by using a JDBC statement. A basic query would look like following:
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/test", "root","root");
Statement statement= conexion.createStatement();
String id="105"; //Here you would need to get the input of the user
String query= "select Salary from Employee where E_ID='"+id+"'";
ResultSet rs=statement.executeQuery(query);
Another way more seccure would be using Prepared Statement to avoid SQL injection.
String query= "select Salary from Employee where E_ID= ? ";
Connection conexion= DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
PreparedStatement ps= conexion.prepareStatement(query);
sentencia.setString(1, "105");
ResultSet rs = ps.executeQuery();

Related

how to add sql parametrized queries through jdbc java

I have to develop a parameterized sql staement something like this below
select * from tablename where cid = cid
so below is the rest service which is calling a method so the user is passing the input parameters like tablename and cid and basis on that it
will go to database and to that particular table and will retrieve the coulmn values so below is the code now in the below code please advise
how can i change the sql statement to be parametrized so that it will retrieve the value from the table onm the basis of cid input by the user
public String retriveData(#QueryParam("tablename") String tablename,#QueryParam("cid") String cid ) throws SQLException
{
Connection con=null;
PreparedStatement ps=null;
String statement="";
String retString="";
try {
//Class.forName("com.mysql.jdbc.Driver");
//put sql jdbc jar in tomcat lib
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con=DriverManager.getConnection("jdbc:sqlserver://xxx:1111; databaseName=aaa", "rr","vvv");
con.setAutoCommit(false);
System.out.println("FROM TABLE NAME : "+tablename);// ***** need to be parametrized query basis on the cid ******
statement="SELECT * FROM "+tablename+";";// ***** need to be parametrized query basis on the cid ********
System.out.println("STATEMENT : "+statement);
ps=con.prepareStatement(statement);
// Turn use of the cursor on.
//ps.setFetchSize(50);
ps.setMaxRows(10);
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
String name=rsmd.getColumnName(5);
while(rs.next())
{
retString=retString+name+" : "+rs.getString(name)+"<br>";
System.out.println(retString);
}
You can't. You need to contruct the sql with string concatenation/placeholder with String.format. prepared statement is for the column values not for table name.
Sources: How to use a tablename variable for a java prepared statement insert
How to pass table name to a Prepared Statement in a SELECT COUNT query?
I'm not sure about why you wanted to parametrized the table name.
But parametrized for cid is OK by using the prepared statement like below.
statement="SELECT * FROM " + tablename + " where cid = ?";
preparedStatement.setInt(1, cid);
If you want to retrieve values from specific table by filtering with cid, that will be the answer I guess.

When checking in the database, the output is repeating / looping

I only clicked the button once, but the output is 2. I wonder if there is something wrong with my condition in the while loop? Or should I use a different approach?
As you can see in the picture, I entered only one data, but the output, executes the conditions in
if and else;
String pass = PF.getText();
String user = TF.getText();
Connection con = connect.getConnection();
Statement st;
ResultSet rs;
String query = "SELECT username, password FROM users";
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
if(user.equals(rs.getString(("username")))){
if(pass.equals(rs.getString(("password")))){
System.out.println("Logged In!");
}else{
System.out.println("Error");
}
}else{
System.out.println("Not in the database!");
}
}
st.close();
As per your table, you have two rows. And, you execute following query, it will return two rows.
String query = "SELECT username, password FROM users";
You could add username and password in where clause instead.
PreparedStatement stmt = connection.prepareStatement("SELECT username, password FROM users where username =? AND password=?");
stmt.setString(1, userid);
stmt.setString(2, pass);
Better use PreparedStatement to avoid any sql injection.
In below line you are selecting all the rows in users table
String query = "SELECT username, password FROM users";
You need to limit it to specific one that you want using WHERE clause.
Wikipedia about WHERE clause:
WHERE clauses are not mandatory clauses of SQL DML statements, but can
be used to limit the number of rows affected by a SQL DML statement or
returned by a query. In brief SQL WHERE clause is used to extract only
those results from a SQL statement, such as: SELECT, INSERT, UPDATE,
or DELETE statement.
Like below:
String query = "SELECT username, password FROM users WHERE username = '"+yourVariable+"' password = '"+yourVariable+"'";
I did this using String concatenation. This will lead to SQL injection. So you can use PreparedStatement as #Ravi mentioned.
Oracle doc. about PreparedStatement:
A SQL statement is precompiled and stored in a PreparedStatement
object. This object can then be used to efficiently execute this
statement multiple times.
Also this question may help you.

Oracle :SQL command not properly ended

String req="INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)";
I want to make a request with Conditions but I get the error:
SQL command not properly ended
You have an invalid SQL query. Here's your current SQL statement:
INSERT INTO NOTIFICATIONS VALUES(6,1,sysdate,'toz',02542,'bporp')(SELECT valide from mouvement where valide=?)
If we split this into several lines for better understanding, you will have this:
INSERT INTO NOTIFICATIONS
VALUES(6,1,sysdate,'toz',02542,'bporp')
(SELECT valide from mouvement where valide=?)
Which is not a valid statement, not even for any SQL tool. That's because you have 2 statements without separating them: an INSERT and then a SELECT, and you're not executing an INSERT INTO <TABLE1> SELECT ... FROM <TABLE2>.
You should execute a single SQL statement per Statement or PreparedStatement. This, in Java, should be done like this:
String sql1 = "INSERT INTO NOTIFICATIONS"
+ " VALUES(6,1,sysdate,'toz',02542,'bporp')";
String sql2 = "SELECT valide from mouvement where valide=?";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql1);
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, <parameter_value>);
ResultSet rs = pstmt.executeQuery();

alternative to jdbc resultset rs.next()

I have a first resultset within which I have to iterate through userids and for each userid, I have to perform several select count(*)'s all of which return single valued outputs. If you haven't understood what I said, please follow the pseudo code below:
ResultSet rs = stmt.executeQuery("select userid from tablename");
while(rs.next()){
String userid = rs.getString("userId");
ResultSet rs1 = stmt.executeQuery("select count(*) as cnt1 from xxx.... where userId = "+userId);
if(rs1.next())
String count1 = rs1.getString("cnt1");
rs1.close();
ResultSet rs2 = stmt.executeQuery("select count(*) as cnt2...");
if(rs2.next())
String count2 = rs2.getString("cnt2");
rs2.close();
....
rs10.close();
Since this is inefficient, I was hoping to get past Resultset each time by writing some sort of direct query to retrieve each different count like
String cnt1 = stmt.executeQuery("select count(*) as noE from useractiontable where curr_action='edit'" + " and userId = " + userId).getString("noE");
I know something like this cannot be done without using rs.next() each time. Is prepare statement the way to go? Is there another way? Appreciate any pointers in this regard.
You can use group by to retrieve all the user with count(*)
ResultSet rs = stmt.executeQuery("select userid,count(*) from tablename group by userid");
I suspect that you can do all the DB work in one query and then just have one result set to read. It would be much more efficient and much cleaner code. I am thinking something like:
select userid, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid
If you have other columns in tablename that you want, you would add them to the select and to the group-by. For example:
select userid, username, count(*) as cnt
from tablename t inner join othertablename ot on t.userid = ot.userid
group by userid, username
The above queries will not return userid's with a count of zero. If you want the ones with zeros, use an outer join (and make the counting logic deal with the null case):
select userid, username, isnull(count(ot.userid), 0) as cnt
from tablename t left outer join othertablename ot on t.userid = ot.userid
group by userid, username

Retrieving data from mysql using JDBC

I'm trying to retrieve some data from an SQL table using JDBC through the BufferedReader, the code I wrote for this execution:
System.out.println("Type a name");
String nname = br.readLine();
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/VetTest", "root", "root");
Statement stmt=(Statement) con.createStatement();
String query = "select * from Pet WHERE name LIKE '?%'";
ResultSet rs=(ResultSet) stmt.executeQuery(query);
while(rs.next())
System.out.println(rs.getString("name"));
if (petn.equals(query)) {
System.out.println("Searching names.." + nname + query);
}
I don't know if I'm doing it wrong, so to summarize my question, I'm trying to retrieve some data depend about what the user inputs in the console. E.g. I'm trying to search for the name Jack in my database I want my application to search for this person's name or a similar person name.
The result I always get when I enter a petname (even though the pet the name is available in my database):
No such a name
You haven't told us what the problem was, but I see one problem:
WHERE name LIKE '?%'
That is incorrect. The clause should be
WHERE name LIKE ?
and you should prepare a statement, bind a string containing the wildcard (%), and then execute this prepared statement:
PreparedStatement stmt = con.prepareStatement("select * from Pet WHERE name LIKE ?");
stmt.setString(1, name + "%");
ResultSet rs = stmt.executeQuery();
Read the tutorial about prepared statements.
If i'm not wrong u wanted to search name which could be a part in some other names also.
For example if u type Jack
The values of Jackson,Helen Jack should also be retrieved from database.Then change the query as
System.out.println("Type a name");
String nname = br.readLine();
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/VetTest", "root", "root");
Statement stmt=(Statement) con.createStatement();
**String query = "select * from Pet WHERE name LIKE '%nname%'";**
ResultSet rs=(ResultSet) stmt.executeQuery(query);
while(rs.next())
System.out.println(rs.getString("name"));
if (petn.equals(query)) {
System.out.println("Searching names.." + nname + query);
}

Categories

Resources