Java mysql like command - java

I want to ask for help my code that will find relevant name from database according to id number.
My code find the name that i try to find.
BUT i want to send an error message when the program can not find ID number.
I tried many ways but always when it couldnt find ID number, it said build succesfull and show no error just quitted the program.
Thanks for your help.
public void search(String ID) throws SQLException {
Statement mystate = con.createStatement();
String sql = "SELECT*FROM users" +
" WHERE id LIKE " + ID;
ResultSet rs = mystate.executeQuery(sql);
while (rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
}
}

Two big issues with your code:
You don't put SQL quotes around ID, so it looks like a keyword or identifer to the SQL parser
It's wide open to SQL-injection attacks (see below)
You want to use a PreparedStatement, which deals with both of those for you. Then just use a flag for whether you saw anything:
public void search(String ID) throws SQLException {
boolean sawOne = false;
PreparedStatement mystate = con.prepareStatement(
"SELECT * FROM users WHERE id LIKE ?"
);
mystate.setString(1, ID);
ResultSet rs = mystate.executeQuery(mystate);
while (rs.next()) {
sawOne = true;
System.out.println("Your Name is " + rs.getString("name"));
}
if (!sawOne) {
System.out.println("...");
}
}
I'm assuming ID already has a wildcard on it (or that you really don't want one).
Or if you know there will be only one match, or you only want one match even if there's more than one, you can add a
mystate.setMaxRows(1);
...before executeQuery(), and then just use if/else, no need for the flag:
if (rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
} else {
System.out.println("...");
}
Obligatory SQL-injection link: http://bobby-tables.com/
And cartoon:

public void search(String ID) throws SQLException {
Statement mystate = con.createStatement();
String sql = "SELECT*FROM users" +
" WHERE id LIKE " + ID;
ResultSet rs = mystate.executeQuery(sql);
if(rs.next()) {
System.out.println("Your Name is " + rs.getString("name"));
}
else
{
System.out.println("Id not found");
}
}

Related

Java PreparedStatement doesn´t set value

I´m totally new to Java and I try to set up a little test to read some data from a MSSQL-database. I have to pass some values to the query but that does not work properly, if I set them manually it works, in my case with the PreparedStatement and the .setLong-Method it does not work.
public class db_testClass {
public static void main(String[] args) throws ClassNotFoundException {
long firstId = 0;
long lastId = 201801001010010403L;
PreparedStatement statement;
int counter = 1;
String SQL = "IF OBJECT_ID('tempdb..#tmpDaten') IS NOT NULL
" DROP TABLE #tmpDaten;
" SELECT DISTINCT
" RIGHT(10000000 + ISNULL(r.xxx, 0), 7) AS Wert
" INTO #tmpDaten
" FROM dbo.xxx
" WHERE r.xxxx BETWEEN firstId = ? AND lastId = ?;
" SELECT DISTINCT
" 'xxxx' AS Art ,
" t.xxx
" FROM #tmpDaten
" LEFT JOIN xxxxxxx a ON a.xxxx = t.xxxx
" AND a.ART = 'xxxx' " +
" WHERE a.xxxx IS NULL;";
String connectionUrl = "jdbc:sqlserver://xxxxxx:1433;databaseName=xxxxxx;integratedSecurity=true;";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
try {
Connection con = DriverManager.getConnection(connectionUrl);
statement = con.prepareStatement(SQL);
statement.setLong(1, firstId);
statement.setLong(2, lastId);
System.out.println(statement);
ResultSet rs = statement.executeQuery();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
The error says that there is wrong syntax nearby the '='......
Anyone any ideas?
Thanks,
Daniel
Your usage of the BETWEEN operator is suspicious and probably just an outright syntax violation. It should be something like:
something BETWEEN low-value AND high-value
to test if the something lies between the values low-value and hi-value.

find a name in a sqlite table and return the id?

What I'm trying to do seems simple but I get this error SQLITE_ERROR] SQL error or missing database (no such column: user1)
public String getIdUser(String name) {
try {
this.stat = conn.createStatement();
String sql = "SELECT id_user FROM User WHERE name = " + name;
ResultSet user = stat.executeQuery(sql);
return user.toString();
} catch (SQLException e) {
return null;
}
}
Replace
String sql = "SELECT FROM User WHERE name = " + name;
with
String sql = "SELECT * FROM User WHERE name = " + name; // you can also specify a column/columns instead of *
I see many problems in your code :
First
Your query should return something it should be :
SELECT col_name1, col_name2, ... FROM User ...
Or if you want to select every thing :
SELECT * FROM User ...
Second
String or Varchar should be between two quotes, your query for example should look like :
SELECT col_name1 FROM User WHERE name = 'name'
Third
I don't advice to use concatenation of query instead use Prepared Statement it is more secure and more helpful (I will provide an example)
Forth
To get a result you have to move the cursor you have to call result.next()
Fifth
Name of variable should be significant for example ResultSet should be ResultSet rs not ResultSet user
Your final code can be :
PrepareStatement prst = conn.prepareStatement("SELECT colName FROM User WHERE name = ?");
prst.setString(1, name);
ResultSet rs = prst.executeQuery();
if(rs.next()){
reuturn rs.getString("colName");
}
Without quoting the name string it's interpreted as column name, and thus the error you see. You could surround it with single quotes, but that's still generally a bad practice, and will leave the code vulnerable to SQL injection attacks.
Additionally, you're missing the select list (specifically, the id_user column), and missing getting it from the result set.
And finally, you forgot to close the statement and the result set.
If you put all of these corrections together, you should use something like this:
public String getIdUser(String name) {
try (PreparedStatmet ps =
conn.prepareStatement("SELECT id_user FROM User WHERE name = ?")) {
ps.setString(1, name);
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
return rs.getString(1);
}
}
} catch (SQLException ignore) {
}
return null;
}

Can't print information from SQL in Java

The user must choose a Resort ID from the table that is displayed and the make a booking. I can't seem to find my problem, I want to print the name of the Resort that they are making a booking at.
String x = jTextFieldID.getText();
Integer Resort = Integer.valueOf(x);
int resort = Integer.parseInt(x);
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+Resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
You have to use rs.next() :
ResultSet rs = pstmt.executeQuery(sql);
String resortName = "";
if(rs.next()){//<<-----------------------------
resortName = rs.getString("RESORT_NAME");
}
JOptionPane.showMessageDialog(null, "You want to book at "+resortName);
If you want to get many results you can use while(rs.next){...} instead.
Note? for a good practice, don't use upper letter in beginning for the name of your variables ResortName use this instead resortName
You need to test over the ResultSet result before trying to read from it:
if(rs.next()) {
String ResortName = rs.getString(1);
JOptionPane.showMessageDialog(null, "You want to book at "+ResortName);
}
And you can use getString(1) to get the RESORT_NAME, check ResultSet .getString(int index) method for further details.
The error is that sql is passed to Statement.executeQuery(String) too, instead of the PreparedStatement.executeQuery().
int resort = Integer.parseInt(x);
//String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = ?";
String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = " + resort;
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
//pstmt.setInt(1, resort);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
String resortName = rs.getString("RESORT_NAME");
JOptionPane.showMessageDialog(null,
"You want to book at " + resortName);
}
}
} catch (SQLException ex) {
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex);
}
Commented is the alternative usage of a prepared statement (as normally used).
Also you should close statement and result set, which can be done automatically with try-with-resources as above.
Oh, oversaw almost, that rs.next() must be called. (The others already mentioned.)

PreparedStatement doesn't change anything

I wrote this code after an example i found on the net but it doesn't work, could you please tell me what is possibly wrong with it. It seems to do something and prints out the result but nothing changes.
package com.company.Start;
import java.sql.*;
public class PreparedStmt
{
public static void main(String[] args) throws Exception
{
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#PC:1521/XE","ACCOUNT", "password");
PreparedStatement updateDB = con.prepareStatement("UPDATE Customers SET lname=? WHERE name=?");
updateDB.setString(1, "Meier");
updateDB.setString(2, "Peter");
updateDB.execute();
Statement smt = con.createStatement();
String query = "SELECT * FROM customers";
ResultSet rs = smt.executeQuery(query);
System.out.println("NAME LNAME ADRESS");
while (rs.next()) {
String name = rs.getString("name");
String lname = rs.getString("lname");
System.out.println(name + " " + lname);
}
}
}
Try "... WHERE name LIKE ?" and for value put "%Peter%"
I guess the name is not matched, because there is a blank or something.
Mind that the above will also change entries like "Peter-Alexander" or "Hans-Peter".
So this is just a prove that it is the value not being matched exactly.
Try using updateDB.executeUpdate() instead of updateDB.execute() . Strangely execute does not work for data updates in most of the cases.
Your code seems fine.
What is the value (int) returned by updateDB.executeUpdate();?
What does a DB utility (like SQLFront) produce given the same statement?
Try con.setAutoCommit(true); and updateDB.close();

Looking up data in database from user

I am trying to let a user lookup a football result, and the database displays that result from the database, but i keep getting this error:
Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.
This is my "useFootballBean.java" bean:
package results;
import results.*;
import java.util.*;
import java.sql.*;
public class UseFootballBean
{
public static void main(String[] args)
throws SQLException, ClassNotFoundException
{
Scanner keyboard = new Scanner(System.in);
String home;
ResultsBean resultsBean = new ResultsBean();
System.out.print("\nEnter Team: ");
home = keyboard.next();
home = resultsBean.getHome(home);
if (home.equals(null))
System.out.println(
"\n*** No such Team ***");
else
System.out.println("\nTeam " + home);
}
}
This is my "resultsBean.java" bean
package results;
import java.sql.*;
public class ResultsBean
{
private Connection connection;
private Statement statement;
private ResultSet results;
public String getHome(String enter)
throws SQLException, ClassNotFoundException
{
String query;
String team = null;
connectAndCreateStatement();
query = "SELECT * FROM Results WHERE homeTeam = "
+ enter;
results = statement.executeQuery(query);
if (results.next())
team = results.getString("homeTeam");
connection.close();
return team;
}
private void connectAndCreateStatement()
throws SQLException, ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"jdbc:odbc:FootballData","","");
statement = connection.createStatement();
}
}
I think you are missing the single quotes required in where clause of query while comparing against a string value. Here you go:
where keyword_name='"+keyword_name+"'"
query = "SELECT * FROM Results WHERE homeTeam = " + '"+ enter + "'";
Since your query parameter is a string, you need to enclose it in quotes:
"SELECT * FROM Results WHERE homeTeam = '" + enter + "'";
However, this is still a bad approach, because it leaves you vulnerable to SQL injection (Remember Bobby Tables?), and will break if the user enters a team name containing quote characters (like England's Greatest Team). Therefore, you should use a PreparedStatement (see Java tutorial).
You are missing single quotation in your Sql Query
query = "SELECT * FROM Results WHERE homeTeam = '"
+ enter+"'";
OR with PreparedStatement to accept quotation
PreparedStatement stmt = null;
String sql;
ResultSet rows=null
try {
sql = "select * from Results where homeTeam=?"
stmt = theConn.prepareStatement(sql);
stmt.setString(1, "Team with ' are permitted!");
rows = stmt.executeQuery();
stmt.close();
}
catch (Exception e){
e.printStackTrace();
}
finally { if (stmt != null) {
stmt.close();
}
Thanks

Categories

Resources