Insert optional field values to mysql from jdbc - java

I have written a code to insert data from jdbc textfield to mysql DB .
String res ="INSERT INTO reservation(check_in_date,check_out_date,cus_id,room_no,Username,nights,adults,kids) VALUES ('"+Startdate+"','"+Lastdate+"','"+cusNo+"','"+Roomno+"','"+Username+"','"+Nights +"','"+Adults +"','"+Kids +"')";
stm=link.prepareStatement(res);
stm.execute();
In this code Kids variable can be null and I have set its' default value to null in database.
But when I enter data from GUI I should always input values for Kids otherwise I can't insert data to the table.
So I must always enter zero to the Kids if I don't need to use that field.
Is there any way to insert data without input Kids when there is no need to use that field?

You are using PreparedStatement incorrectly. You should not concatenate values into a query, but use parameter placeholders instead. This prevents SQL injection and it is usually cleaner.
You can set values to null this way.
String res = "INSERT INTO reservation(check_in_date,check_out_date,cus_id,room_no,Username,nights,adults,kids)"
+ " VALUES (?,?,?,?,?,?,?,?)";
try (PreparedStatement stm=link.prepareStatement(res)) {
stmt.setDate(1, startDate);
// ... other variables
// Option 1, assuming kids is an object (eg Integer)
stm.setObject(7, kids);
// Option 2, kids is int and other condition used to determine if null,
// explicitly set null or set value:
if (kidsIsNull) {
stm.setNull(7, Types.INTEGER);
} else {
stm.setInt(7, kids);
}
stm.executeUpdate();
}

As you are using prepare statement you can add logic to use setNull method for preparedStatement something like this :
if( kids == null){
stm.setNull(#ParamerterNo ,java.sql.Types.INTEGER);
}else{
stm.setInt(#ParamerterNo ,kids);
}

Related

SQL in java return wrong data

I have a java method like this one below:
public String qE (String query, String selector) throws QSLException, IOException{
//I get my sqlQuery from properties
String sqlQuery = properties.getPRoperty(query);
//sqlQuery = SELECT count(?) FROM employees WHERE ? is not null
PreparedStatement ps = conn.preparedStatement(sqlQuery);
ps.setFetchSize(100);
ps.setString(1,selector);
ps.setString(2,selector);
ResultSet rs = ps.executeQuery();
String rs = "";
while(rs.next()){
queryValue = rs.getString(1);
}
return queryValue;
}
When I run it with parameters
qe(employees, second_name)
then this query should be executed:
SELECT count(second_name)
FROM employees
WHERE second_name is not null
The problem is that non of employees has second name and I should get 0 and the whole method should return 0 but I always get diffrent number greater than zero.
Can anyone tell me why this doesn't return 0 but always diffrent number like i.e. 2399?
A ? represents a value not an object name, so it is equivalent to using
SELECT count('second_name')
FROM employees
WHERE 'second_name' is not null
Which is always true and is always counted. In other words, your query counts all rows in table employees.
You cannot use parameters to parameterize object names. If you really need to do this dynamically, you will need to construct the query dynamically (by concatenating the name in the query string). Just be sure to guard yourself against SQL injection if you do that (eg by checking the name against a white list or comparing explicitly to the database metadata).

How to get an information string, int from SQL, but the information must not be initialized?

I want to get some informations in my SQL base, but i don't know how to. I have already used this following code :
String pseudo = null;
String query = "select * from UsersInfos where Pseudo=?"
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, pseudo);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
pseudo = rs.getString("Pseudo");
}
System.out.println(pseudo);
But it returns me null of
System.out.println(pseudo);
I want to get some informations, not set them, well can some one helps me please ?
Your result set is coming back empty. In other words, the assignment pseudo = rs.getString("Pseudo") never took place.
The reason the result set is empty (i.e. contains no records) is due to the WHERE clause:
select * from UsersInfos where Pseudo=null
The comparison of any value in the Pseudo column to null will be either null or false (depending on your particular RDBMS). This means that no records will match.

java,how to consult sql lite if a value of a variable "varConsult" is in column "protocolo" in table "pessoajuridica",

i tryed this:
ResultSet existetabela = stm.executeQuery ("SELECT * FROM pessoajuridica WHERE protocolo =" + varConsult );
System.out.println(existetabela);
but it only return a strange String -> org.sqlite.RS#1f959518
i was expecting the value..
remembering, sql lite and java :S
i want to use the value that it return to compare, if it return any value, means that it exist, so it will not add to the sql, if dont return anything = can add!!!
("if exist" doesnt work for me, says that its a invalid argument in the sql command line --')
You can use ResultSet#next() method to test whether there was any result set returned:
if (existetabela.next()) {
// Result was fetched
// Assuming type of protocol is String (Can be anything)
String protocol = existetabela.getString("protocolo");
} else {
// No result
}
Now, let's move ahead to the major issue. You should use PreparedStatement, to save yourself from SQL Injection.
You need to iterate inside the result set to retrive the actual data that were found:
while (existetabela.next()){
System.out.println(existetabela.getObject("protocolo"));
}
Did you look at PreparedStatement ?

ResultSet NullPointerException

I have a stored procedure, I want to call it from JDBC, I got null pointer exception in the line"
while (restuls.next()) {
My code is:
Connection con = Database.getConnection();
CallableStatement callableStatement = null;
try {
String storedProcedure = "{call getAllCustomerAddresses(?,?,?,?,?,?,?)}";
callableStatement = con.prepareCall(storedProcedure);
callableStatement.setInt(1, this.getID());
callableStatement.registerOutParameter(2,
java.sql.Types.INTEGER);
callableStatement.registerOutParameter(3,
java.sql.Types.VARCHAR);
callableStatement.registerOutParameter(4,
java.sql.Types.INTEGER);
callableStatement.registerOutParameter(5,
java.sql.Types.INTEGER);
callableStatement.registerOutParameter(6,
java.sql.Types.INTEGER);
callableStatement.registerOutParameter(7,
java.sql.Types.VARCHAR);
callableStatement.execute();
System.out.println(callableStatement.getInt(2));
System.out.println(callableStatement.getString(3));
System.out.println(callableStatement.getInt(4));
System.out.println(callableStatement.getInt(5));
System.out.println(callableStatement.getInt(6));
System.out.println(callableStatement.getString(7));
ResultSet restuls = callableStatement.getResultSet();
while (restuls.next()) {
int addressID = restuls.getInt(2);
String label = restuls.getString(3);
int regionID = restuls.getInt(4);
int areaID = restuls.getInt(5);
int cityID = restuls.getInt(6);
String description = restuls.getString(7);
this.addresses.add(new CustomerAddressImpl(this, label,
description, RegionImpl.getInstance(regionID),
AreaImpl.getInstance(areaID), CityImpl
.getInstance(cityID), addressID));
}
look at the code, the System.out.println is working , and It is printing the right values from database, so why the results set is null please??
another thing, I must use result set because the stored procedure returns many rows.
I am really confusing why I can print the right values but the result set is null
Thanks in advance
Edit
If you want to give you the stored procedure tell me please
Stored Procedure
ALTER PROCEDURE [dbo].getAllCustomerAddresses(
#customerID INT,
#addressID INT OUTPUT,
#label VARCHAR(200) OUTPUT,
#regionID INT OUTPUT,
#areaID INT OUTPUT,
#cityID INT OUTPUT,
#description TEXT OUTPUT
)
AS
SET NOCOUNT Off;
SELECT #addressID = [ID],
#label = [label],
#regionID = [regionID],
#areaID = [areaID],
#cityID = [cityID],
#description = [description]
FROM Customer_Address
WHERE customerID = #customerID
execute() method of PreparedStatement returns true if result set presents and false otherwise. You do not check the return value of execute(). I think that if you do that you see that it is false.
The reason should be in your stored procedure that IMHO does not return value. So, try to analyze it to understand the problem.
Here are recommendations I can give you:
Use executeQuery() that directly returns ResaultSet instead of execute(). I think this is more convenient.
Avoid using stored procedures that couple your platform independent java code with specific type of database. Try to write all logic in java and use portable SQL statements only.
The last time I saw pure JDBC code was about 10 years ago. There are a lot of tools that help you to avoid writing SQL inside java code. Take a look on JPA, Hibernate, iBatis etc.
Your stored procedure doesn't actually produce a ResultSet because you are using output parameters (not 100% sure, I don't have a SQL Server handy to test).
You may just need to call CallableStatement.getObject(int) or CallableStatement.getObject(String) (or a type specific getter) to get the values instead. If you want to process as a ResultSet, then you should not use the output parameters in your stored procedures, but write the stored procedure as a select without assigning to output parameter. That will create a result set from the stored procedure
Another possibility might by that your stored procedure is first returning one or more update counts before returning the result set. The boolean return value of execute() indicates whether the first result is an update count or a ResultSet. You will need to repeatedly call getMoreResults() and getUpdateCount() to be sure you have processed every result.
Your posted stored procedure contains SET NOCOUNT OFF which signals to SQL Server (or Sybase) that you want update (and I believe select) counts returned as well, you might want to try using SET NOCOUNT ON.
You can also try to process the results of execute() like this to find out if there are indeed multiple update counts etc before the result set:
boolean result = pstmt.execute();
while(true)
if (result) {
ResultSet rs = pstmt.getResultSet();
// Do something with resultset ...
} else {
int updateCount = pstmt.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
// Do something with update count ...
}
result = pstmt.getMoreResults();
}
See also Java SQL: Statement.hasResultSet()?

Use of getters in ResultSets

I am trying to write java code to access a table 'customer' with columns 'customer_id', 'email', 'deliverable', and 'create_date'
I have
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "SELECT * FROM customer WHERE customer_id LIKE " + customerId;
ResultSet rtn = constat.executeQuery(query);
Customer cust = new Customer(rtn.getInt("customer_id"), rtn.getString("email"), rtn.getInt("deliverable"), rtn.getString("create_date"));
conn.close();
return cust;
I am receiving the error:
java.sql.SQLException: Before start of result set
As far as I can tell, my error is in the line where I am creating a new Customer object, but I cannot figure out what I am doing wrong. Can anyone offer me some help? Thanks!
You must always go to the next row by calling resultSet.next() (and checking it returns true), before accessing the data of the row:
Customer cust = null;
if (rtn.next()) {
cust = new Customer(rtn.getInt("customer_id"),
rtn.getString("email"),
rtn.getInt("deliverable"),
rtn.getString("create_date"));
}
Note that you should also
use prepared statements instead of String concatenation to avoid SQL injection attacks, and have more robust code
close the connections, statements and resultsets in a finally block, or use the try-with-resources construct if using Java 7
Read the JDBC tutorial
You should call ResultSet.first() to move the result to the first position. The result set is a programming convention not to retrieve the whole result of the query and keep in memory. As such, its interface is quite low level and you must explicit select the row via methods like first(), last() or next() (each returns true to check if the requested row index is in the set)
You need to add
rtn.next();
before you use the result set.
Usually this is done as
while (rtn.next()) {
<do something with the row>
}

Categories