Basically I have a table name java_db.Customer with the columns CustomerID,
Name, Address and FinanceOK.
Basically I want to write a simple query that says if FinanceOK = true JOptionPane.ShowMessage "Finance Accepted"
Otherwise FinanceOK = False JOptionPane.ShowMessage "Finance Declined".
What is the the best way to go about writing this query?
Now, there's a lot of information in your post that is missing but down and dirty here is how you might accomplish the task:
long customerID_Variable = 232; // .... whatever you have to provide customer ID number ....
String customerName = "John Doe"; // .... whatever you have to provide customer name ....
boolean financeOK = false; // default financing approval flag
String message = "Finance Declined!"; //default message
// Catch SQLException if any...
try {
// Use whatever your connection string might be
// to connect to your particular Database....
Connection conn = DriverManager.getConnection("jdbc:derby:c:/databases/salesdb jdbc:derby:salesdb");
conn.setAutoCommit(false);
// The SQL query string...
String sql = "SELECT FinanceOK FROM Customer WHERE CustomerID = " + customerID_Variable + ";";
// Although it is best to use the Customer ID to reference a
// particular Customer you may prefer to to use the Customer
// name and if so then use the query string below instead...
// String sql = "SELECT FinanceOK FROM Customer WHERE Name = '" + customerName + "';";
// Execute the SQL query...
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
//Retrieve the data from the query result set...
while (rs.next()) {
financeOK = rs.getBoolean("FinanceOK");
}
//Close everything...
rs.close();
stmt.close();
conn.close();
}
catch (SQLException ex) { ex.printStackTrace(); }
int msgIcon = JOptionPane.ERROR_MESSAGE;
if (financeOK) {
message = "Finance Accepted!";
msgIcon = JOptionPane.INFORMATION_MESSAGE;
}
JOptionPane.showMessageDialog(null, message, "Financing Approval...", msgIcon);
Related
I have written a program that extracts data from an SQL table:
String url = "jdbc:mysql://localhost/petcare";
String password = "ParkSideRoad161997";
String username = "root";
// Step 2: Making connection using
// Connection type and inbuilt function on
// Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
// Try block to catch exception/s
try {
Connection con = DriverManager.getConnection(url, username, password);
// SQL command data stored in String datatype
String sql = "select * from inbox";
p = con.prepareStatement(sql);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("inboxId");
int inboxId;
// Condition check
while (rs.next()) {
inboxId = rs.getInt("InboxId");
// System.out.println(inboxId);
}
String sql2 = "select * from message where inboxId = int";//this is where i need help
p = con.prepareStatement(sql2);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("Inbox:");
}
// Catch block to handle exception
catch (SQLException e) {
// Print exception pop-up on screen
System.out.println(e);
}
Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.
I tried the query string sql and it works now I just need to fix String sql2.
String sql2 = "select * from message where inboxId = " + 1234;
1234 could be a variable. You could also use String.format() to do it as well.
String sql2 = String.format("select * from message where inboxId = %d", 1234);
Try this:
String sql2 = "select * from message where inboxId = ?"; //The ? indicates a variable in the prepared statement.
p = con.prepareStatement(sql2);
p.setInt(1, inboxId);
rs = p.executeQuery();
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;
}
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.
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 having a hard time understanding why this wont work, if I type the exact same thing straight into a MySQL console it accepts it but when ever I try to run it, it reports a syntax error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '= '6'' at line 1
All I'm trying to do is receive the data in the row with the member_id value of whatever the user inputs. For testing purposes the value is always 6, I have tried parsing it as int instead of a string, which gave the same error, and I tried just adding the ID variable onto the end of the string instead of using a place holder but it didn't like that much either.
Here is the code:
public class MemberDAO {
public PreparedStatement ps = null;
public Connection dbConnection = null;
public List<Member> getMembersDetails(String ID) throws SQLException{
List<Member> membersDetails = new ArrayList();
String getMembershipDetails = "SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members"
+ "WHERE member_id = ?";
try {
DBConnection mc = new DBConnection();
dbConnection = mc.getConnection();
ps = dbConnection.prepareStatement(getMembershipDetails);
ps.setString(1, ID);
ps.executeQuery();
ResultSet rs = ps.executeQuery(getMembershipDetails);
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String phoneNumber = rs.getString("phone_number");
String email = rs.getString("email");
String over18 = rs.getString("over_18");
String dateJoined = rs.getString("date_joined");
String dateExpired = rs.getString("date_expire");
String fines = rs.getString("fines");
Member m;
m = new Member(firstName, lastName, phoneNumber, email, over18, dateJoined, dateExpired, fines);
membersDetails.add(m);
} catch (SQLException ex){
System.err.println(ex);
System.out.println("Failed to get Membership Details.");
return null;
} finally{
if (ps != null){
ps.close();
}
if (dbConnection != null){
dbConnection.close();
}
} return membersDetails;
}
This is what's calling it:
private void btnChangeCustomerActionPerformed(java.awt.event.ActionEvent evt) {
customerID = JOptionPane.showInputDialog(null, "Enter Customer ID.");
MemberDAO member = new MemberDAO();
try {
List membersDetails = member.getMembersDetails(customerID);
txtFullName.setText(membersDetails.get(0) + " " + membersDetails.get(1));
} catch (SQLException ex) {
System.err.println(ex);
System.out.println("Failed to get Details.");
JOptionPane.showMessageDialog(null, "Failed to retrieve data.");
}
}
Any input is appreciated.
Your query is missing a space:
...fines FROM members"
+ "WHERE...
Will result in
FROM membersWHERE
Which is invalid SQL
Change it to
+ " WHERE....
your query is:
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM
members WHERE member_id = ?
So between member and where you need a blank character
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members WHERE member_id = ?