How can I achieve this code? - java

Hey I have a problem with my java codes. If I enter a text in my IDFiELD and then press the "Enter" And then message come out "ID wasn't recognize, Try again..." but it shows the values in my table. So how can i address that problem.
So here is my code in java eclipse:
IDField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evnt) {
if (evnt.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String query = "select * from employee where IDNo = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, IDField.getText());
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
int count = 0;
while (rs.next()) {
count += 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "ID Verified!");
IDField.setText(null);
} else {
JOptionPane.showMessageDialog(null, "ID was'nt recognize, Try again...");
}
rs.close();
pst.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
I hope you can help me. Thanks.

Your method table.setModel(DbUtils.resultSetToTableModel(rs)); consumes the ResultSet already, so you cannot use it again to count how many results you received.
You can:
run the query twice (simplest to code, but least clean and efficient)
query the table model to see if there are rows
extract the results of the query into a datastructure and convert that to your table model and also use it to check if there were results

Related

How can you get a JTextField to work in a SQLite Select statement?

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

Java updating mysql row if id already exists

I have a simple form with 5 fields. (txtID, txtFirstName, txtLastName, txtCheque, txtSavings). All I want to do is inserting these fields into my database table "accounts". Before that step I want to check if the ID from my txtID field already exists in my database. If yes then I want to update the database row with the content from the fields. And if not I want to create a new row with the content. So far the check if the ID exists in my DB works but if click on my btn I get the following error message: I dont relly know what I'm doing wrong.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near '(LastName,
FirstName,Cheque,Savings) VALUES('Tester','Markus','450.00','50.00" at
line 1
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String id = txtID.getText();
String checkid ="SELECT * FROM accounts where ID=?";
pst=conn.prepareStatement(checkid);
pst.setString(1, id);
rs = pst.executeQuery();
boolean recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if(recordAdded){
// the statement for inserting goes here.
}else{
String sql ="UPDATE accounts SET " + "(LastName,FirstName,Cheque,Savings) VALUES" + "(?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.executeUpdate();
getAllAccounts();
JOptionPane.showMessageDialog(null, "Customer Updated");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
getAllAccounts();
}
catch(Exception e) {
}
}
}
do you let me to make some changes in your code?
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "UPDATE accounts SET LastName = ?, FirstName = ?, Cheque = ?, Savings = ? where id = ?";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.setString(5,txtID.getText());
int updatedRowCount = pst.executeUpdate();
// no record with id = txtID
if(updatedRowCount == 0) {
pst.close();
sql = "insert into accounts (ID,LastName,FirstName,Cheque,Savings) values (?,?,?,?,?,?) ";
pst = conn.prepareStatement(sql);
pst.setString(1,txtID.getText());
pst.setString(2,txtLastName.getText());
pst.setString(3,txtFirstName.getText());
pst.setString(4,txtCheque.getText());
pst.setString(5,txtSavings.getText());
pst.executeUpdate();
}
getAllAccounts();
JOptionPane.showMessageDialog(null, updatedRowCount > 0 ? "Customer Updated" : "Customer Inserted");
}
catch(Exception e){
getAllAccounts();
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
pst.close();
}
catch(Exception e) {
}
}
}

MySQL Query based on user input in Java

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 '%'

Combine Select and Update statement

I have tried to research this problem however I cannot find a solution.
Background: I have a small java program using sqlite as its DB. I am trying to update a row counter to keep track of how many time a code is searched, or how many times a row is displayed. (If a row is not displayed it will not be counted). My database table hase three columns {Codes, Description, ItemCount}
Here is code that I used to get a row
private void SrchCodeActionPerformed(java.awt.event.ActionEventevt) {
String sql = "SELECT * FROM emdcodes WHERE Codes like ?"; // SQL command
try {ps = conn.prepareStatement(sql);
ps.setString(1, EMDCODELOOKUP.getText() + "%");
rs = ps.executeQuery();
ResultsTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} }
I am using this sql code on a website version and it works. it is written in PHP.
$sqlcount = mysql_query("update emdcodes SET ItemCount = ItemCount +1 Where Codes like '$term%'");
My Question is where and how would I add the counter code to the java progam. The purpose of the counter is to maintain a list of the top 5 items searched for.
I thank anyone for their help.
I am not sure if this is exactly what are you looking for...
private void SrchCodeActionPerformed(java.awt.event.ActionEventevt) {
if (counter <= 5) {
String sql = "SELECT * FROM emdcodes WHERE Codes like ?"; // SQL command
try {ps = conn.prepareStatement(sql);
ps.setString(1, EMDCODELOOKUP.getText() + "%");
rs = ps.executeQuery();
if (rs.first()){
counter++;
}
ResultsTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
first() ->
Moves the cursor to the first row in this ResultSet object.
Returns:
true if the cursor is on a valid row; false if there are no rows in the result set

check if the record exists in database

I need to check the box no if exist in the database under the remittance id that I enter if the box no exists then i need to show the message that the box no already exists but if it doesn't the it should insert new box i have written some code but its showing error
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(1, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
while(rs.next()){
rs.equals().txtboxno.getText());
}
JOptionPane.showMessageDialog(rootPane, "hello!S");
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
Try this code
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
/// Do your insertion of new records
recordAdded = true;
}
if( recordAdded ){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
or you could use a count:
String query = "select count(*)
from dbo.soil_det where rm_id = ? and box_no = ?";
then after executing the query you get the count with
rs.getInt(1)
using that you can decide which info to show to the user
very First You have to get count using sql if count is greater than zero then do not insert records and show message like already exists and in else part insert record. see following example
private boolean findCount(int rm_id,String box_no)
{
int count=0;
//write query here
count = assign query result;
//check count
if(count>0)
{
return false;//records exists
}else{
return true;//records do not exists
}
}
public void insertData()
{
if(findCount(1,"1")){//pass values
//Write down your insert logic
}else{
JOptionPane.showMessageDialog(rootPane, "Records Already Exists");
}
}
Note: Friend in Your Example you have not written the insert logic. only select was there
First you could add -- on the db table -- a unique constrain on the columns (rm_id, box_no), this is anyway a good thing to do.
Then you could simply try to insert the box and catch the exception and check if it is a violation of the unique constraint.
Another option (still keeping the unique constraint) would be to make a more complicated SQL insert statement that inserts only if not existing, you may google "sql insert if not exist" to find some examples...
You need to get the appropriate record from the ResultSet e.g.
boolean found = rs.getString(1).equals().txtboxno.getText());
At the moment you're simply comparing the ResultSet object itself to a string, and that won't work. The above pulls the first record from the ResultSet and performs the comparison on that (note: your datatype may be different and you may need rs.getInt(1) etc.)
Perhaps its sufficient in your case just to check if you have a ResultSet result (via rs.next())
simplified version
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
if(!rs.next()){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
rs.next() followed by if condition returns true if the record exists in a table. if not, return false.

Categories

Resources