Retrieving data from mysql using JDBC - java

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);
}

Related

Retrieve data from database by java & myphpadmin

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();

You have an error in your SQL syntax; near 'Type='1'' at line 1 - I cant write correct SQL query

I have created a SQL login system in java but want and what to only allow people with account type 1 to access the program. The query I have written keeps coming up as errors. THE SECURITY OF THE PROGRAM IS NOT A CONCERN AS ITS JUST FOR COURSEWORK
public void login(){
try{
int a = 0;
int b =1;
String query ="select * from Users where Login = '"+
main_menu.login_text.getText()+"' and Password='"
+main_menu.passwordtext.getText().toString()+"' and Account Type='" +1+
"'" ;
rs =st.executeQuery(query);
System.out.println("Records from Database");
if(rs.next()){
f=2;
query ="select * from Users where Login = '"+
main_menu.login_text.getText()+"' and Password='"
+main_menu.passwordtext.getText().toString()+"' and Account Type='" +0+
"'" ;
rs =st.executeQuery(query);
System.out.println("Records from Database");
}
else if (rs.next()){
f=1;
}
else{
JOptionPane.showMessageDialog(null, "Incorrect Username
and Password...");
con.close();}
} catch(Exception ex){
System.out.println("Error"+ex);
}
As #luk2302 have suggested, you should change your code. With that code, you allow to be easily breach your security.
Here is an example of how to make it better:
PreparedStatement pst = null;
String sql = "SELECT * FROM login where username=? and password=?";
pst = con.prepareStatement(sql);
pst.setString(1,user);
pst.setString(2,pass);
ResultSet rs = pst.executeQuery();
Now you can just get the data you just recovered to get the information about the user. If no resul set is given, the login would have failed.

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.

How to assign a Value taken from the database to a label?

I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

How do I verify password entered is the password associated with entered email?

Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);

Categories

Resources