How can I pass integer into string for sql query - java

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

Related

Java JDBC throwing an error for an SQL query asking to return details from only particular rows

I have a database called 'airplane' inside which there is a table named booking.
The booking table has the columns phone(int type) ,name(text type),address(text type),city(text type) destination(text type),date(text type). I want to fetch only the rows whose phone column has value or data equal to phone number entered by the user . I wrote the following code for it . For context , I am using java using JDBC
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/airplane";
static final String USER = "root";
static final String PASS = "";
Connection conn = null;
try
{
System.out.println("enter cell no");
int cell=sc.nextInt();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
// My SQL SELECT query.
String query = "SELECT * FROM `booking` where phone=cell";
// creating the java statement
Statement st = conn.createStatement();
/** executing the query, and getting a java resultset of all rows whose phone
column has the value equal to one entered by user and stored by me in
int variable cell**/
ResultSet rs = st.executeQuery(query);
//iterate through the java resultset
while (rs.next())
{
int Phone = rs.getInt("phone");
String Name = rs.getString("name");
String Address = rs.getString("address");
String City = rs.getString("city");
String Destination = rs.getString("destination");
String Date = rs.getString("date");
// print the results
System.out.format("%d, %s, %s, %s, %s, %s\n", Phone, Name, Address, City, Destination, Date);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
I am getting the error:
Got an exception!
Unknown column 'cell' in 'where clause'
What am I doing wrong?
Try this:
String query = "SELECT * FROM `booking` where phone=" + cell;
A better way to handle this is to use PreparedStatement
This case, the query would look like:
String query = "SELECT * FROM `booking` where phone=?"
and
statement.setInt(1, cell);
you will see it's gonna run
String query = "SELECT * FROM booking where phone="+"\"%s\"";
query=String.format(query,cell);

JAVA GUI - GET and SHOW DATA FROM MYSQL

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.

SQL Query Java Net Beans

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

Java JDBC query not accepted

Hey I'm making a little webapp and have a java file in it with a function what connects a db and fetches the data.
But I'm getting a exception anyone knows why because my query is valid if I'm right.
I use eclipse and mysql workbench.
Function:
import java.sql.*;
public class Functions {
public void dbConn(String nVal, String inpVal){
System.out.println("Running function...");
if(nVal != null || inpVal != null){
String sqlSerch;
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
//driver / db path
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/profile";
//DB user&password
final String USER = "root";
final String PASS = "";
//declare con & sql var
Connection conn = null;
Statement stmt = null;
//register jdbc driver
try{
Class.forName(JDBC_DRIVER);
//make a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//SQL Statement
stmt = conn.createStatement();
String sql = "SELECT "+ sqlSerch;
ResultSet rs = stmt.executeQuery(sql);
//Declareer variablen met data uit db
//int id = rs.getInt("ID");
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
System.out.println( naam + aNaam);
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
System.out.println(e);
}
System.out.println(" - " + nVal + " - " + inpVal);
}
}
}
exception:
java.sql.SQLException: Column 'naam' not found.
database structure:
Thank you in advance,
Casper
When you receive "name" through the nVal parameter, you select only ID and aNaam columns.
So, if you try to get values for naam from that ResultSet you get the Exception.
Also, I suggest limiting the results of your query to 1, since you use the WHERE clause with naam and ID, which seem to be not unique, unless there's some constraint not included in the screenshot.
Hope this helped.
You branch and create your queries:
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}
Then regardless of the branch, you get your result set values:
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");
But "naam" will not be in your "ID, aNaam" search.
In general, a good rule of thumb is to always return the same columns.

Netbeans java application - executing query on MySql database

In the project I'm working on I need to execute Searching SQL query i.e the wildcard characters in Java Netbeans.
I'm able to execute simple queries like
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid ="+empid+"");
while(rs.next())
{
String name = rs.getString("name");
String salary = rs.getString("salary");
name1.setText(name);
salary1.setText(salary);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This works completely fine. But now I want to use this MySql query
Mysql>select * from employes where empid like "123%";
instead of this
Mysql>select * from employes where empid =123;
in java Netbeans.
I've tried to do this
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid%+"");
while(rs.next())
{
String id = rs.getString("EmpId");
String name = rs.getString("name");
String salary = rs.getString("salary");
area.setText(id +" "+name+" "+salary+" "+ "\n");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
As you can see that in the 8th line I've inserted the wildcard character(%) but this ain't working. How can I solve this?
Your wildcard character is misplaced.
It should be:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");
In this case the % char will be treated as a wildcard.
If you want to search the % char itself, you have to escape it following the mysql escape rules:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");
Pay special attention to the quotes

Categories

Resources