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.
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();
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 have this piece of code where I prompt the user to enter the depID to edit a department and then through the IF statement I have done it displays either saved or department doesn't exists. Now my problem is that it's going directly to the else statement. When I used debugging I noticed that the RS (ResultSet) is only comaring the users input to the first row of the table which is AOL.
try{
String value1 = txt_depID.getText();
String value2 = txt_depName.getText();
String sql = "Update tblDepartment set depID = '"+value1+"' , depName = '"+value2+"' where depID = '"+value1+"'";
String sql1 = "Select depID, depName from tblDepartment";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
rs = ps.executeQuery();
ps = conn.prepareStatement(sql);
ps.execute();
if(rs.next()){
String depi = rs.getString("depID"); //Issue: only reading first row
if(depi.equals(value1)){
JOptionPane.showMessageDialog(null, "Entry Saved");
}
else{
JOptionPane.showMessageDialog(null, "Department doesn't exist");
}
}
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
You can do this in one cycle. You should be using executeUpdate.
String sql = "Delete from tblEmployee where staffNo=?";
String sql1 = "Select * from tblEmployee";
Class.forName(driver);
conn = DriverManager.getConnection(url);
ps = conn.prepareStatement(sql1);
int result = ps.executeUpdate();
if (result > 0) {
// success
}
Here's what executeUpdate results:
Returns: either (1) the row count for SQL Data Manipulation Language
(DML) statements or (2) 0 for SQL statements that return nothing
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();
i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!