I am trying to insert values into my database via java but I keep getting a "doesn't have a default value" error message. I have looked online to find some help but they haven't really solved my problem. This is the error that I am getting "java.sql.SQLException: Field 'firstName' doesn't have a default value".
import java.sql.*;
class MysqlCon {
public static void main(String[] args) {
String personalID = null;
String firstname = null;
String lastname = null;
String addressone = null;
String addresstwo = null;
String city = null;
String state = null;
String zipcode = null;
String phone = null;
String email = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Address_Book","root","");
Statement stmt = con.createStatement();
personalID ="3";
firstname = "John";
lastname = "Doe";
addressone = "4000 s.c.r. 222";
addresstwo = "5000 n.c.r. 333";
city = "place";
state = "Texas";
zipcode = "43523";
phone = "43523524";
email = "weqtatw#aadf.com";
stmt.executeUpdate("insert into Names(personID) values("+personalID+")");
stmt.executeUpdate("insert into Names(firstname) values("+firstname+")");
stmt.executeUpdate("insert into Names(lastname) values("+lastname+")");
stmt.executeUpdate("insert into addresses(address1) values("+addressone+")");
stmt.executeUpdate("insert into addresses(address2) values("+addresstwo+")");
stmt.executeUpdate("insert into addresses(city) values("+city+")");
stmt.executeUpdate("insert into addresses(state) values("+state+")");
stmt.executeUpdate("insert into addresses(zipcode) values("+zipcode+")");
stmt.executeUpdate("insert into phoneNumbers(phoneNumber) values("+phone+")");
stmt.executeUpdate("insert into emailAddresses(emailAddress) values("+email+")");
con.close();
}catch(Exception e){System.out.println(e);}
}
}
You're currently running three separate insert statements into one table, such as:
INSERT INTO Names (personID) values (3);
INSERT INTO Names (firstname) values ("John");
INSERT INTO Names (lastname) values ("Doe");
You will end up with 3 separate rows, instead of a single row. If any of the columns require a value (i.e. if you have a primary key without an auto_increment), the insert will fail since it will require a value for the column (edit: in this case you have a required value for the firstName field).
You'll also have a very useless table that will contain entries such as a row with nothing but the name "John", a row with nothing but the last name "Doe", and a row with personID of 3.
Instead, you should be running a single INSERT statement, such as:
stmt.executeUpdate("insert into Names(personID, firstname, lastname) values("+personalID+", "+firstname+", "+lastname+")");
Which should also populate all required cells in a row.
Please try to run one of insert into commands in database shell first - you will see that command like insert into Names(personID) values(3) is not correct because DB does not know what to insert into other fields. However, it would know if there is a default value for missing fields - that's why DB is complaining.
If you do not have default values for that table (they are set up while table creation), you must give all values at once like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
Related
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.
I'm working with my project just for a academic purposes where I encounter a SQL problem. Where the Foreign Key its not getting the value of inserted ID. For me to achieve 2nd Normal Form. I split out in an independent tables. And match them up using the SECTION_ID as foreign keys. Here where I create a two tables.
1st Table
2nd Table
SOURCE CODE:
String inputSectionName = Section_SectionName_TextField.getText();
int inputStudentLimit = Section_Student_Limit_ComboBox.getSelectedIndex();
String inputRoomAssign = Section_Student_Limit_ComboBox2.getSelectedItem().toString();
String inputAdviserAssign = Section_Student_Limit_ComboBox1.getSelectedItem().toString();
String inputSession = Section_Session_Settings_ComboBox.getSelectedItem().toString();
String inputYearLevel = Section_Session_Level_ComboBox.getSelectedItem().toString();
String inputSchoolYear = Section_SchooYear_ComboBox.getSelectedItem().toString();
String insertALLSECTION_LIST = "INSERT INTO ALLSECTIONS_LIST (SECTION_NAME)"
+ "VALUES (?)";
String insertALLSECTIONS_SETTINGS = "INSERT INTO ALLSECTIONS_SETTINGS (SECTION_POPULIMIT,ROOM_ASSGN,ADVISER_ASSIGNED,SESSION_ASSIGNED,YRLEVEL_ASSGN,SCHOOL_YEAR)"
+ "VALUES(?,?,?,?,?,?)";
try (Connection myConn = DBUtil.connect())//Connection
{
myConn.setAutoCommit(false);//Turn off auto commit
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
}//end of try
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTIONS_SETTINGS))//Prepared Statement
{
myPs.setInt(1,inputStudentLimit);
myPs.setString(2, inputRoomAssign);
myPs.setString(3, inputAdviserAssign);
myPs.setString(4, inputSession);
myPs.setString(5, inputYearLevel);
myPs.setString(6, inputSchoolYear);
myPs.executeUpdate();
myConn.commit();
JOptionPane.showMessageDialog(null, "Insert Successful");
}//end of try
}//end of try
catch(SQLException e)
{
DBUtil.processException(e);
}//end of catch
When I run my query for the 1st Table it gives me output like this.
But when I run my query for the 2nd Table the SECTION_ID column gives a me null value.
Feel free to comment. If I miss something guide me where I go wrong. Thanks.
It looks like you're assuming the SECTION_ID column in your ALLSECTIONS_SETTINGS table will be automatically populated with the last primary-key value that was inserted into the ALLSECTIONS_LIST table. This doesn't happen.
What you need to do instead is to get the value that was automatically generated for the SECTION_ID column in the first PreparedStatement and set it in the second PreparedStatement.
Here's how to modify your first PreparedStatement to obtain the generated SECTION_ID:
int sectionId;
try (PreparedStatement myPs = myConn.prepareStatement(insertALLSECTION_LIST, Statement.RETURN_GENERATED_KEYS))//Prepared Statement
{
myPs.setString(1,inputSectionName);
myPs.executeUpdate();
myConn.commit();
ResultSet generatedKeys = myPs.getGeneratedKeys();
if (generatedKeys.next()) {
sectionId = generatedKeys.getInt(1);
} else {
throw new SQLException("No generated section ID returned");
}
}
The changes are:
add a new variable sectionId to hold the generated section ID,
add Statement.RETURN_GENERATED_KEYS to the call to prepareStatement on the first line. This tells your database to return the generated value for SECTION_ID.
fetch the generated-keys result-set from the statement and read the section ID out of it..
I'll leave it up to you to modify your second PreparedStatement to set the value for the SECTION_ID column when you insert into ALLSECTIONS_SETTINGS.
I am trying to find regular expression and if there are some duplicates, keep the unique ones and put the rest in a trash table.
but I get this Erro which I do not know what it is!
Here is my code:
public class RegexRemoverMain {
public static void main(String[] args) throws SQLException, ClassNotFoundException{
//Connection Parameters and Connect to Postgres Database
String data = "jdbc:postgresql://localhost:5432/postgres";
Class.forName("org.postgresql.Driver");
Connection conn = null;
//Connect to DB
conn = DriverManager.getConnection(
data, "username", "password");
//statements to get distinct owners
Statement ownerSt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//statement to get Image Ids of a user
Statement ownersImagesIdsSt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertSQL;
//an arraylist to store unique titles+tags reported by user
ArrayList<List<String>> result = new ArrayList<List<String>>();
//list for storing those Ids of a users which are filtered
List<String> filteredIds = new ArrayList<String>();
//list for storing those Ids of a users which are kept
List<String> ids = new ArrayList<String>();
//get the list of all the users
ResultSet distinctOwner = ownerSt.executeQuery("select distinct owner from \"flickrData_bulkUploadedFree\"");
distinctOwner.last();
distinctOwner.beforeFirst();
int count=0;
//RegularExpression Pattern
String theRegex= "((DSC)?(dsc)?(img)?(IMG)?(\\s?)(\\_?)((\\-?))[0-9]{1,9})";
Pattern checkRegex = Pattern.compile(theRegex);
//loop is going through all user's Images and check whether their the titles is one of the patterns if yes, check their title+description which are unique or not
//if yes, we keep them; if not; we throw them away or store in another place
while(distinctOwner.next()){
count = count++;
Statement insertSt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//store filtered images
String insertString = "INSERT INTO regexIamges"
+ "( id , owner, descriptio, title, tags) VALUES"
+ "(?,?,?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertString);
//for each user exist in "flickrData_bulkUploadedFree"
String owner = distinctOwner.getString("owner");
ResultSet ownersImages;
ownersImages = ownersImagesIdsSt.executeQuery("select id, title, tags, descriptio from \"flickrData_bulkUploadedFree\" where owner = '" + owner +"';");
ownersImages.last();
ownersImages.beforeFirst();
//an list of images of a user's with the information about id, title, tags and descriptions in order to find unique Images
ArrayList<List<String>> bulkUploadList = new ArrayList<List<String>>();
while(ownersImages.next()){
String id = ownersImages.getString("id");
String title = ownersImages.getString("title");
String tags = ownersImages.getString("tags");
String description = ownersImages.getString("descriptio");
Matcher regexMatcher = checkRegex.matcher(title);
if (regexMatcher.find()){
if(regexMatcher.group().length() != 0){
List<String> rowsList = new ArrayList<String>();
rowsList.add(id);
rowsList.add(title);
rowsList.add(tags);
rowsList.add(description);
bulkUploadList.add(rowsList);
bulkUploadList.add(rowsList);
}
}
else{
insertSQL = "INSERT INTO \"regBulkfreeFlickrData\" SELECT * FROM \"flickrData_bulkUploadedFree\" where id ='"+id+"';";
insertSt.addBatch(insertSQL);
}
}
HashSet<String> hashSet = new HashSet<String>();
for(List<String> item : bulkUploadList) {
String title, tags, id, desc, uniqueString;
title = item.get(1);
tags = item.get(2);
id = item.get(0);
desc = item.get(3);
uniqueString = (tags + "#" + desc).trim().toUpperCase();
System.out.println(item);
if(!hashSet.contains(uniqueString)) {
result.add(item);
hashSet.add(uniqueString);
insertSQL = "INSERT INTO \"regBulkfreeFlickrData\" SELECT * FROM \"flickrData_bulkUploadedFree\" where id ='"+id+"';";
insertSt.addBatch(insertSQL);
} else {
// System.out.println("Filtered element " + uniqueString + "id " + id);
filteredIds.add(id);
preparedStatement.setString(1, id);
preparedStatement.setString(2, owner);
preparedStatement.setString(3, desc);
preparedStatement.setString(4, title);
preparedStatement.setString(5, tags);
preparedStatement.addBatch();
}
}
preparedStatement.executeBatch();
preparedStatement.close();
insertSt.executeBatch();
insertSt.close();
}
}
and the Error is this:
Exception in thread "main" java.sql.BatchUpdateException: Batch entry 0 INSERT INTO regexIamges( id , owner, descriptio, title, tags) VALUES('4292220054.0000000000000','23352125#N07','NoValue','IMG_2720','NoValue') was aborted. Call getNextException to see the cause.
at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2743)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1928)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:405)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2892)
at uzh.textmining.RegexRemoverMain.main(RegexRemoverMain.java:116)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
and the table is:
CREATE TABLE "RegexImages"
(id numeric,
owner character varying(254),
descriptio character varying(254),
title character varying(254),
tags character varying(254),
PRIMARY KEY (id)
)
thanks hasnae;
I used try catch and I got that the tableName in my code does not match the table Name in database.
another problem was the name of the table: I change all the letters to lower case to solve all the errors.
A problem that looks similar: https://stackoverflow.com/a/39227828/755804
(spoiler:
The total number of values, that is, the number of columns multiplied by the number of rows must not exceed 32767 for a single INSERT statement.
You can divide 32767 by the number of columns to get the maximal number of rows per one SQL INSERT statement.)
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.
Problem was:
Can't get just inserted data from the table. From the error message it looks like it doesn't see the first column. I know the column is there and data was inserted. I checked database. I checked if column Number has some hidden space in name. No it doesn't.
Tried:
Debugged every line and everything was good together with inserting data to database.
Found the issue is almost at the end of the code:
rs1.next();
String s1 = rs1.getString(1);
I tried to write
rs1.first();
String s1 = rs1.getString(1);
or
rs1.first();
String s1 = rs1.getString("Number");
Below I posted my final code that is working correctly and I am able to insert data to the table and display on the browser.
package mypackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/query")
public class CList {
private LinkedList<SMember> contacts;
public CList() {
contacts = new LinkedList();
}
#GET
#Path("/{CList}")
public Response addCLocation(#QueryParam("employeeId") String eId) throws SQLException{
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
PreparedStatement ps0 = null, ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try{
//Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
//Connection variables: dbPath, userName, password
con = (Connection)
DriverManager.getConnection(dbURL,"someusername","somepassword");
System.out.println("We are connected to database");
//SQL Statement to Execute
System.out.print(id);
s = con.prepareStatement("SELECT 1 FROM CList WHERE Number=?");
s.setString(1, eId);
rs = s.executeQuery();
//Parse SQL Response
if(!rs.next()) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) " +
"VALUES (?,?,?,?)");
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhone());
ps.executeUpdate();
ps = con.prepareStatement("SELECT Number, First_Name,
Last_Name, Phone_Number FROM CList
WHERE Number=" + eId);
rs1 = ps.executeQuery();
while(rs1.next()){
result = "[Added contact to contact list.
Number: " + rs1.getString(1) +
"][First_Name: " + rs1.getString(2) +
"][Last_name: " + rs1.getString(3) +
"][Phone_Number: " + rs1.getString(4) +
"]\n";
}
}
else {
result = "[Contact is already on the list]";
}
}
catch(Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
//Close Database Connection
ps0.close();
ps.close();
con.close();
}
}
catch(Exception e) {
System.out.println(e);
}
//Return the Result to Browser
return Response.status(1000).entity(result).build();
}
Table
1234 number is unique and it is a number I want to get.
You see number should be unique. So far I am taking data from the SMember class and it always insers the same data. Purpose of my question is just to ge the information I inserted few seconds ago.
Also, there is SMember class that I didn't post here and in its constructor I initialize number, first name, last name, and phone number. Testing purpose.
I made all recommended changes but problem remains the same.
There is several issues here.
The solution to your question is that you do not let the database generate keys, that is why you cannot ask for the generated keys later.
Look at this line of your code:
ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name, Phone_Number) VALUES ('"+sm.getEmployeeID()+"', '"+sm.getFirstName()+"', '"+sm.getLastName()+"', '"+sm.getPhone()+"')", Statement.RETURN_GENERATED_KEYS);
You later want to retrieve the Number column's value as a generated key. You however do pass a value for that column, namely the return value of sm.getEmployeeID(). If you pass a value, it will not get generated (assuming that this column is defined in database as being auto incremented.
Fixing this however, will not solve everything as your code has quite a lot of issues. Let me list the ones I can directly spot:
You initialize your variable sm by creating a new object. But you will still not have values for employee id, first name, last name or phone number as you nowhere set those values to sm (or do you do that in the default constructor?).
You are trying to use a prepared statement, this is good, but you are actually not doing that, this is very bad as it openes the ground for SQL injection. Instead of creating the query string like you are doing, you should use a fixed string like e.g INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?) and then set the values on the statement before executing it. That way nobody can mess with your database through that statement (read up on SQL injection, just google it to see the issue you would introduce).
Your employee id seems to be the eId parameter of your method. You should use that also in your select statement to see if it is already in your database (use a prepared statement here also) and in your insert statement later when the id is not already in the database.
If you are checking for a specific id, then insert that specific id, it is quite useless to retrieve some generated id. You already have defined your unique identifier. Use that one!
Edit: As your code is kind of a mess, I have cleaned this stuff a bit and fixed the issues that I could directly find. Check if this is helping you:
public Response addCLocation(String eId) throws SQLException {
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s = null;
PreparedStatement ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try {
// Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
// Connection variables: dbPath, userName, password
con = DriverManager.getConnection(dbURL, "someusername", "somepassword");
System.out.println("We are connected to database");
s = con.createStatement();
// SQL Statement to Execute
System.out.print(id);
PreparedStatement alreadyThere = con.prepareStatement("SELECT 1 FROM CList WHERE Number = ?");
alreadyThere.setString(1, eId);
System.out.println("0");
// Parse SQL Response
int i = 0;
if (rs.next() == false) {
SMember sm = new SMember();
ps = con
.prepareStatement("INSERT INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) VALUES (?,?,?,?)");
ps.setString(1, sm.getEmployeeID());
ps.setString(2, sm.getFirstName());
ps.setString(3, sm.getLastName());
ps.setString(4, sm.getPhone());
ps.executeUpdate();
}
else {
result = "[Contact is already on the list]";
}
}
catch (Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
// Close Database Connection
s.close();
ps.close();
con.close();
}
}
catch (Exception e) {
System.out.println(e);
}
// Return the Result to Browser
return Response.status(200).entity(result).build();
}
You are getting this error because your first query is wrong it is returning an empty resultset.
Firstly,
rs = s.executeQuery("SELECT 1 FROM CList WHERE Number='id'");
the above line in your code is not correct it should be like this:
**rs = s.executeQuery("SELECT 1 FROM CList WHERE Number="+id);**
then the correct query will be fired to database.
Secondly,there is problem in following code
if(rs.next() == false) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO CList (Number, First_Name, Last_Name,
Phone_Number) VALUES ('"+sm.getEmployeeID()+"',
'"+sm.getFirstName()+"', '"+sm.getLastName()+"',
'"+sm.getPhone()+"')",
Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
In the above code you should initialize the SMember, object currently in query they are going as null also the when you are using PreparedStatement you should use the query like this:
**ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhoneNumber());**
The Query statement maybe an issue "SELECT 1 FROM CList WHERE Number='id'",In select statement your id is taken as a String.we need to replace with value.
-->Try like this {"SELECT 1 FROM CList WHERE Number="+id},
-->One more thing "select 1 from table name" will print 1 for no of rows avail for your condition.
So my suggestion is
{"SELECT * FROM CList WHERE Number="+id}
try This!!
"SELECT 1 FROM CList WHERE Number='id'"
It looks like you're trying to actually select records where the Number value is 'id'. That may be causing the error when you try to do the "rs.next()" command on an empty result set. Are you instead trying to do something like
"SELECT 1 FROM CList WHERE Number=' " . id . "'"? Where "id" is a variable?