i'm new to SQL and Java and couldn't find anything to fix my problem.
(closest thing: MySQL query based on user input)
So I have a DB full of shows/events and I want users to "search" for a certain event or show.
The user will input the name of the show/event into GUI and I want the query to return data associated with the user-input.
For example:
User is searching for the artist Zedd;
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE 'zedd' ");
The query is fixed, can the query be modified to search whatever the user input?
Something like:
String artist = "zeppelin"
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE "artist" ");
Thanks in advance for the help!
You should double check your shows second column. I'm not sure you can use a column named date. Anyway, you should certainly use a PreparedStatement with something like,
String sql = "SELECT eventname, eventdate FROM shows WHERE artist LIKE ?";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
ps.setString(1, artist);
rs = ps.executeQuery();
while (rs.next()) {
String eventName = rs.getString("eventname");
Date eventDate = rs.getDate("eventdate");
// Use your columns in your row here.
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
As per normal SQL, you statement would work if it was
String artist = "'%zeppelin%'";
searchSet = statement.executeQuery("SELECT eventname,date FROM shows WHERE artist LIKE " + artist);
The String needs to be aurrounded with % and also quoted.
Have a look at preparedStement though, it has method to set each parameter separately and avoid SQL injection.
It would be something like this:
String artist = "zeppelin"
searchSet = statement.executeQuery("SELECT eventname, date FROM shows WHERE artist LIKE '%" + artist + "%'");
Note the sql wildcard string '%'
Related
I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output
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;
}
UPDATE
i changed sql query (just test it and it works on sql but still not working with java dont no why :(
Hi how to add get result on jLabel with this code? and is it possible to show results on jTable?
private void searchTeacherActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = ("select student_ID, firstName, afterName FROM student JOIN studentHom ON course = studentHom_ID WHERE prefect = ?
try {
pst = connection.prepareStatement(sql);
pst.setString(1, larareSoka.getText());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}
First don't use (?) you can just use ?:
select ... where course.courseStart = ? and course.corse.end = ?
Second you have to set parametters to your query in your case you have tow, so you have to use :
pst.setString(1, value_of_courseStart);
pst.setString(2, value_of_corse.end);
Third to get results you have to use ResultSet like this :
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString(1);
//----------------------------------^
//...same for the other columns
}
or you can use the name of column like this:
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString("firstName");
//--------------------------------------^^
//...same for the other columns
}
Note
If you want to get multiple result you ca use while instead of if.
Your query is a little wired why you are using :
course.courseStart = (?) and course.corse.end = (?)
//no point---^ ^------Why this point here
Did you mean course.courseStart = ? and course.corseEnd = ?
ResultSet rs = pst.executeQuery();
String firstname = rs.getString("firstname");
..
jLable.setText(firstname);
...You need to read the data from the resultset
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.)
I'm trying to find out if data from my DB matches user input. I have tried this code, but its not doing what I need it to do. I would like it to display a message saying whether or not they match.
try {
String find = BC.getText(); //Get text from Textfield
String sql = "select * from Inventory where Barcode=?";
st = con.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
if("Barcode".equals(find))
{
JOptionPane.showMessageDialog(null,"Matching");
}
else JOptionPane.showMessageDialog(null,"not matching");
}
} catch (Exception ex) {
}
Put the parameter that you want to search.See this;
String find = BC.getText(); //Get text from Textfield
String sql = "select * from Inventory where Barcode=?";
st = con.prepareStatement(sql);
st.setString(1, "12345678");//Set Barcode value.
rs = st.executeQuery();