I am creating an SQL that stores information about customers, and want all the customers to have unique contact numbers, essentially as an identifier for themselves. However my validation for my SQL seems to run even if the number already exists within the SQL, and am unsure of what is going wrong.
public static boolean uniqueValidation(String contactNum){
Connection c = null;
Statement stmt = null;
boolean result = true;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:custInfo.db"); //this is telling the code where to retrieve the data from that it is looking for.
stmt = c.createStatement();
String sql = "SELECT rowid AS isFound FROM CUSTINFO WHERE CONTACTNUMBER LIKE "+contactNum+""; //collecting a rowid from custinfo, if the number is found anywhere
ResultSet rs = stmt.executeQuery(sql);
String compareString = rs.getString("isFound"); //setting the value from the resultset of rowid to comparestring
if(!compareString.isEmpty()){ //if there is a value return false
result = false;
}else{
result = true; //else return true as there is no value
}
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return result;
}
Related
I wrote this function for checking id where name is given in database but it always returns false:
public boolean checking(String name,String Id_number,String tableName){
if(conn==null){
System.out.println("db is not connect,is gonna connect");
connect();
}
try{
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from "+tableName+" where name ="+"'"+name+"'");
if(Id_number.equals(rs.getString(4))){
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
How I can fix this
When a ResultSet is created, it points to the "before-first" row of the result. You need to attempt to advance it to the first row (using next()), and then compare its content. If there is no such row, you can return false:
public boolean checking(String name, String id_number, String tableName){
if (conn==null) {
connect();
}
try{
Statement stmt = conn.createStatement();
// Side note: Depending on where the parameters come from, this may be vulnarable
// to an SQL Injection attack.
// Make sure you properly validate/sanitize the arguments
ResultSet rs = stmt.executeQuery("select * from " + tableName + " where name = " + "'"+name+"'");
// Check if there's even such a row:
if (!rs.next()) {
return false;
}
// Check the id number
return Id_number.equals(rs.getString(4));
} catch(Exception e){
e.printStackTrace(); // Or some proper handling...
}
return false;
}
After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.
Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}
Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.
so I am a beginer in JDBC - SQL Programming. I need a little advice which is most probably about SYNTAX.
So, Problem = I'm trying to search a record which has name(string provided in function argument) in the record. Following is my code. Now I've designed this code in such a way that there can be more than 1 records with the same name, so all of that records' data will be printed (by ShowData() Function).
protected static void SearchbyName (String toCompareName)
{
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
boolean flag = false; //to confirm if record has found atleast once
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT idEmployee FROM employee WHERE name = ' "+toCompareName+" ' ");
if( !(rs.next()) ) //if ResultSet is not empty
{
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
}
if(flag==false) //if no record found
{
JOptionPane.showMessageDialog(null, "ERROR:: No Records Found..", "Not Found", JOptionPane.ERROR_MESSAGE);
}
//close connection
if(rs!=null)
{ rs.close(); }
if(stmt!=null)
{ stmt.close(); }
if(conn!=null)
{ conn.close(); }
}
catch(SQLException e)
{ System.err.println(e); }
catch(Exception e)
{ System.err.println(e); }
}
So here it is. As far as my understanding goes, there is some problem with either RESULTSET rs or the Query I'm executing.
Kindly help. & if you can suggest a better approach for search, sure do please. I'm going to write 4 more functions SearchbyAge, SearchbyQualification, SearchbySpecialization on the same pattern.
Just this is enough
while(rs.next()) //reading all records with the same name, extracted by Query
{
int foundID = rs.getInt("idEmployee"); //extracting ID of found record
ShowRecord(foundID); //prints record of foundID fromDB
flag = true; //set flag
}
You don't have to check the data in resultset this way with a if case
if( !(rs.next()) )
This will move to the next record in the resultset
SOVLED
My error was in query. I was putting spaces in string's syntax which I was comparing.
WRONG = `"(.. WHERE name = " ' +toCompareName+ '" ");
RIGHT = `"(.. WHERE name = "'+toCompareName+'" ");
So thats it. Hope it helps to anyone else. :)
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.
I have table VIDEO (VideoID int Primary Key, Address Varchar(100)) and I want to search table to see if there is video with given address. But I am not sure if this code works good, and if this could be better done.
Here is my code:
public boolean checkIfVideoExist(String address) throws SQLException {
int count = 0;
Statement stmt = connection.createStatement();
ResultSet rset = stmt
.executeQuery("SELECT Count(VideoID) from VIDEO WHERE Address='"
+ address + "'");
if (rset.next())
count = rset.getInt(1);
if (count == 0)
return false;
else
return true;
}
Be sure you have an index set on column ADDRESS. Then your query should run fast.
It is better to use a prepared statement to pass the address value to the query. And you should close the result set and the statement.
And
if (count == 0)
return false;
else
return true;
looks a bit strange.
public boolean checkIfVideoExist(String address) throws SQLException {
int count = 0;
PreparedStatement stmt = null;
ResultSet rset = null;
try {
stmt = connection.prepareStatement(
"SELECT Count(VideoID) from VIDEO WHERE Address=?");
stmt.setString(1, address);
rset = stmt.executeQuery();
if (rset.next())
count = rset.getInt(1);
return count > 0;
} finally {
if(rset != null) {
try {
rset.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e) {
e.printStackTrace();
}
}
}
}
The code is fine, except for the way you're embedding strings in your query. If address contains a quote character, the query will become invalid. And this is only a small part of the problem. Doing it like this opens the door to SQL injection attacks, where malicious users could enter an address which completely changes the meaning of the query.
Always use prepared statements to bind parameters:
PreparedStatement stmt = connection.prepareStatement("SELECT Count(VideoID) from VIDEO WHERE Address=?");
stmt.setString(1, address); // proper escaping is done for you by the JDBC driver
ResultSet rset = stmt.executeQuery();
Also, you should use finally blocks to close your result sets and statements.
Your code is vulnerable to SQL Injection, it should use a prepared statement instead of building the SQL query via string concatenation.
Apart from that, it looks OK.
ResultSet rset = stmt.executeQuery("SELECT * from VIDEO WHERE Address='" + address + "'");
return rset.next();
then there is at least one matching record and you are done. No need for aggregate function count() ....