Displaying SQL select result on JAVA - java

How do I display SQL result with system print?
Here are my code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/oopdb","root","12345");
st = con.createStatement();
//set query
String s = "SELECT Category FROM infocollected WHERE Adminno='123'";
//save query result into rs
rs = st.executeQuery(s);
//retrieve category from result
String category = rs.getString("Category");
//print out result to console
System.out.println("category");

while (rs.next()) {
String category = rs.getString("Category");
System.out.println(category);
}
And check if your DB is not Empty

You shouldn't surround variables with double quotes. And also take a loot at #Gatusko's answer.
Replace it with:
// ...
//retrieve category from result
String category = rs.getString("Category");
//print out result to console
System.out.println(category);

When you want to print a variable, there is no need to indicate it with "" . Just only the variable name.
For example if you use your code, your console is showing: category
However if you use System.out.println(category); your console will print the value of the variable.

Related

Can't get my jsp to store the integer value from my result set

All I am trying to do is pull the integer value from the cell. When I run the command in my sql workbench I get the proper value screenshot of db output however when I execute the code in programming environment I get "An exception occurred processing [/registration.jsp] at line [24]" which is this line idnum = rs.getInt("MAX(idnum)")+1; The program has an initial html page where the use enters the desired password, first name and last name. it then sends the info to the jsp which is supposed to take that information increment the user id by 1 from whatever the highest value is currently then create a new table entry with said information.
int idnum = 0;
String pwd = request.getParameter("pwd");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment2", "root",
"has the actual password in the code");
Statement stmt = conn.createStatement();
String query = "SELECT MAX(idnum) FROM users";
ResultSet rs = stmt.executeQuery(query);
idnum = rs.getInt("MAX(idnum)")+1;
Replace
idnum = rs.getInt("MAX(idnum)")+1;
with
if (rs.next())
idnum = rs.getInt(1)+1;
Note that without calling the next() method, the result set pointer/cursor will not move to the 1st row (from default position).
This should work:
String query = "SELECT MAX(idnum) as maxNum FROM users";
ResultSet rs = stmt.executeQuery(query);
if(rs.next(){
idnum = rs.getInt("maxNum")+1;
}

rs.next() is returning false in while statement

So, I'm trying to extract msgID and msgStatus values from database for each reference Id(variable msgRefList) stored in the list object and I'm trying to store these extracted values in String objects for further processing. But rs.next() method is returning false and hence it is not going into the while loop where the assignment statements are. I checked in database with the query that i'm using in the code and it shows one record in the result, but still rs.next() is returning false. Screenshot attached with the database results.
Below is the actual code that i'm using
List<String> msgRefList = listofRefrnceValues:
try {
Connection connect = connectToDB(ENV);
for(String reference: msgRefList){
String query="select ID, MSG_STS from TABLE where INSTR_ID = ?";
PreparedStatement stmt = connect.prepareStatement(query);
stmt.setString(1,reference);
ResultSet rs = stmt.executeQuery();
if(rs!=null){
while(rs.next()) {
P_MID = rs.getString("P_MID");
P_MSG_STS = rs.getString("P_MSG_STS");
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
You have some typos in your SQL-Query-String in java. Instead of TABLE you probably meant MINF (your real table) also all of your properties don't have the prefix P_ and ID is probably MID. So change:
String query="select ID, MSG_STS from TABLE where INSTR_ID = ?";
To:
String query="select P_MID, P_MSG_STS from MINF where P_INSTR_ID = ?";
And you'll be fine.

How to assign NULL value to a string and then insert it in mysql database

Here I'am calculating the average of one column
If the avg comes to be 0.0, then i would want to assign the string variable as NULL else the avg value itself.
These values are getting stored in mysql db
Now my problem is that when the avg does come 0.0, string NULL gets stored but i want the default NULL value to get stored in it.
How can i assign NULL (and not string NULL) to variable ans??
private void btnAdd1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost/check","root","");
st = conn.createStatement();
String sql4 =("SELECT AVG(unit4) as num FROM lo where unit4 IS NOT NULL");
PreparedStatement pstmt3 = conn.prepareStatement(sql4);
ResultSet rs4 = pstmt3.executeQuery();
rs4.next();
double a3 = rs4.getDouble("num");
double b3 = Math.round(a3*10);
double res5 = b3/10;
rs4.next();
avg1.setText(String.valueOf(res5));
String a1 =avg1.getText();
String ans ;
if(a1.equals("0.0")){
ans = null;
}else{
ans = a1;
}
String query = "INSERT INTO chk(id) VALUES ('"+ans+"')";
executeSQlQuery(query, "Inserted");
}
You can use setNull() and to avoid any syntax error or SQL Injection you have to use PreparedStatement instead :
PreparedStatement ps = connection.prepareStatement("INSERT INTO chk(id) VALUES (?)");
ps.setNull(1, java.sql.Types.VARCHAR);
ps.executeUpdate();
Note
Something wired in your program, why you are using rs4.next(); what if your result is empty, i think you need something like this instead :
if (rs4.next()) {//<<<--------------------
double a3 = rs4.getDouble("num");
//-----------^^-----------------
}
You have not enclose ans between quotes to handle the NULL case.
Otherwise, indeed you insert "NULL" String :
String query = "INSERT INTO chk(id) VALUES ('"+ans+"')";
You can try :
String query = "INSERT INTO chk(id) VALUES ("+ ans +")";
Your code is pretty suboptimal, since you're not even using a PreparedStatement. Since your query contains the '' markers, it will always insert a string in the database. In the case of null you'll just be inserting 'null' which isn't what you want.
Now, this is not a good solution, but it's the quickest for you. Modify the query to "INSERT INTO chk(id) VALUES ("+ans+")", and add the following before executing the query:
if(ans != null)
ans = "'" + ans + "'";
Remember, this is bad code. It's not the standard way. It has security issues. Learn to use a PreparedStatement.

Fill jTextField with records when selecting from jComboBox (Java database)

How do you go about putting records into a jTextField when an item is selected from a jComboBox? For example, I'm making an airline reservation system and I have a combo box with the available flights. Below it are text fields with designated info like departure date, departure time, arrival date, etc. How do I make it so that when the user selects an item from the the combo box, (ex. flight name is CX9005) the corresponding info from the same row is shown in the text fields? (ex. departure date is November 12 2015)
EDIT:
So I tried doing that with the ff. code, but I got a syntax error and a ResultSet not open error.
private void combo_FlightItemStateChanged(java.awt.event.ItemEvent evt) {
try{
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
rs = stmt.executeQuery(query);
}
catch(SQLException err){
JOptionPane.showMessageDialog(UserModule.this, err.getMessage());
}
}
Also, I use this function to connect to my database if that matters.
public void DoConnect() {
try{
String host = "jdbc:derby://localhost:1527/UserAccounts";
String uName = "Bryan";
String uPass = "Cruz";
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ACCOUNTS";
rs = stmt.executeQuery(sql);
}catch(SQLException err){
JOptionPane.showMessageDialog(Connect.this, err.getMessage());
}
}
Also, I might not have been too clear with my original post. I want to make it so that when the user selects a flight from the combo box, all of that flight's details show up in the appropriate text fields. (ex. departure date, departure time, destination, etc.) I'm confused on how to make this work so help would be much appreciated!
You get the text from the comboBox using getSelectedItem() or getSelectedValue().
You can then create a MySQL query like:
String flightName = yourComboBox.getSelectedItem().toString();
String query= "Select * from yourTable where flightName = \'"+flightName+"\';";
Then you can execute this query using executeQuery()
Now for the part with setting results in all testfields
First store the result in a ResultSet object
rs = stmt.executeQuery(query);
rs.next();
Now you have the result in object rs
Use rs.getString(columnNumber) to get records from the result
Eg.
String departureDate = rs.getString(4);
// assuming the column number is 4
Do this to get all required strings.
And set them in respected columns using setText() method
flightID = combo_Flight.getSelectedItem().toString();
String flightName = combo_Flight.getSelectedItem().toString();
What is the point of the above two statements? You can't get two values from the same combo box. Either you get the flightID or the flighName.
String query = "Select * from ACCOUNTS where flightName = \'"+flightName+"\';";
but I got a syntax error
Don't try to build the SQL string manually. Instead you can use a PreparedStatement. It will make sure the proper delimiters are used so you just concentrate on the SQL statement:
String flightName = combo_Flight.getSelectedItem().toString();
String query = "Select * from ACCOUNTS where flightName = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString( 1, flightName );
ResultSet rs = stmt.executeQuery();
So you will need access to the Connection object you established in the doConnect() method. Note, method names should NOT start with an upper case character.
Also, I believe the standard for database column names is to capitalize the words of the column, so you should be using "FlightName" not "flightName" as the column name.

Update Data Records on MySQL using user input

Ok I have this issue. I need to update a record on my DB but I am having trouble because of my SQL syntax. By pressing the "Update Name" button, 2 messages pop up and the user selects the former name and the new name for the Table. But the statement is never executed and the names wont change. My main goal is to "resolve" the id from the 1st statement to a variable
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
and add it here
String name = "UPDATE consoles SET name = ? WHERE id = ?";
Is it possible to resolve to a variable the id I get from my 1st statement?
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name_1 = "SELECT id FROM consoles WHERE name LIKE ? ";
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
PreparedStatement psname_1 = conn.prepareStatement(name_1);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strin);
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.
Arguments are switched.
psname.setString(2,"%" +strout+ "%");
psname_1.setString(1,"%"+strin+"%");
should be
psname.setString(2, "%" + strin + "%");
psname_1.setString(1, strout);
try
{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test1?user=me&password=12345");
String name = "UPDATE consoles SET name = ? WHERE name LIKE ?";
PreparedStatement psname = conn.prepareStatement(name);
String strin = JOptionPane.showInputDialog(null,"Previous Name : ");
String strout = JOptionPane.showInputDialog(null,"New Name : ");
psname.setString(1,strout);
psname.setString(2,"%" +strin+ "%");
psname.executeUpdate();
Statement stmtname = conn.createStatement();
// show the updated table
ResultSet rsname = stmtname.executeQuery("SELECT * FROM consoles INNER JOIN hardware ON consoles.id=hardware.id");
.
.
.
ADDING THEM TO A JTABLE
.
.
.

Categories

Resources