Java sql Data pulling in the columnName but not the data - java

On this java method I am trying to get data from a ms-sql server. I am trying to get the int value from a column , Now the columns I am using are all int's but for some reason when i try pulling it as a INT I am getting a number format error saying that the column is a nvarchar. Not sure what is happening and when i ran the System.out I am noticing I am only pulling the column name but no data that the column has. Here is my method, I am not sure what I am doing wrong or what is missing from this. Any help will be greatly appreciated thank you.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
String type = getTypeOfTimeOff().replaceAll("\\s+","");
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = "SELECT ? FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getTypeOfTimeOff().replaceAll("\\s+",""));
preparedStatement.setString(2, getEmpName());
preparedStatement.setString(3, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
//int checker = rs.getInt(1);
String acheck = rs.getString(1);
System.out.println("TIME off the user has : " + acheck);
int checker = Integer.valueOf(acheck);
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}

try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
int aCheck = rs.getInt("column name");
}
}catch(){}
like this

For some reason what i did was add an AS to my query along with adding a if statement to my code caused the resultset to work with my code and allowed me to pull numbers from my database. Thank you for your help. Here is the updated code i added if it helps anyone.
private boolean CheckEmployee(long bDays) throws ClassNotFoundException, SQLException {
PreparedStatement preparedStatement;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, userName, password);
String selectProject = null;
if(getTypeOfTimeOff().equalsIgnoreCase("Vacation Day"))
selectProject = "SELECT VacationDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Bonus Day"))
selectProject = "SELECT BonusDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
else if(getTypeOfTimeOff().equalsIgnoreCase("Birthday Day"))
selectProject = "SELECT BirthdayDay As dayList FROM EmpVacationTbl Where FullName =? "
+ "AND ManagerName =?";
System.out.println("Query String : " + selectProject);
preparedStatement = conn.prepareStatement(selectProject);
preparedStatement.setString(1, getEmpName());
preparedStatement.setString(2, getManagerName());
System.out.println(preparedStatement.toString());
try (ResultSet rs = preparedStatement.executeQuery())
{
while (rs.next())
{
int checker = 0 ;
checker = rs.getInt("dayList");
System.out.println("Days the user has off are: " + checker );
if(checker < bDays)
{
conn.close();
message = "Too many days";
return false;
}
else
{
conn.close();
return true;
}
}
if (rs.wasNull()) {
{
conn.close();
message = "Unable to find the days";
return false;
}
}
}
conn.close();
message = "Information not matching recordings.";
return false;
}

Related

java.sql.SQLException: No operations allowed after statement closed

I updated my database from SQLite db to MySQL and I suddenly I get this error:
java.sql.SQLException: No operations allowed after statement closed.
public boolean isEnough(int quantity, String item) throws SQLException {
boolean enough = false;
PreparedStatement pst = null;
ResultSet rs = null;
String sql = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if (rs.next()) {
int temp = rs.getInt(3);
if (quantity > temp) {
stmt.close();
enough = false;
} else if (quantity <= temp) {
enough = true;
int updatedStock = temp - quantity;
String sql_1 = "UPDATE Stock SET Item_quantity ='" + updatedStock + "' WHERE Item_name ='" + item + "'";
stmt.executeUpdate(sql_1); //error here
String sql_2 = "SELECT * FROM Stock WHERE Item_name='" + item + "'";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
System.out.println(rs);
if (rs.next()) {
int isZero = rs.getInt(3);
if (isZero == 0) {
String sql_3 = "DELETE FROM Stock WHERE Item_name = '" + item + "'";
stmt.executeUpdate(sql_3);
JOptionPane.showMessageDialog(this, "Order Added\nItem is now out of Stock and removed from Stock database automatically.");
}
}
}
}
stmt.close();
return enough;
}
I'm closing connection and statement after every update, but I have no idea how to fix this error. If I go back to SQLite db this error disappears. I'm new to MySQL, so pardon me if I'm doing something wrong.

How to validate data using sql statement to ensure user does not breach the system

I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}

How do I return the contents of a ResultSet as a map?

I would like to know how I can return a result set from a query as a map.
This is my query where 'nameCodesString' is a list of strings e.g. ('raul', 'peter', 'shawn'):
try (PreparedStatement stmt = conn.prepareStatement("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
log.info("rs {}",rs);
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
}
The result should be a code and a value. I am not sure how I can do this all in one connection to the database.
Hello that is my suggestion
String req="select n.CODE, l.VALUE from TNAME n join"
+" TPROPERTIES l on n.UIDPK = l.OBJECT_UID "
+" where n.CODE IN ?";
PreparedStatement stmt=null;
ResultSet rs=null;
try{
stmt=conn.prepareStatement(req);
stmt.setString(1, nameCodesString);
rs=stmt.executeQuery();
while(rs.next()){
nameCode = rs.getString(1);
displayName = rs.getString(2);
Person.add(new PersonDTO(nameCode, displayName, ""));
}
}
catch(SQLException ex){
System.out.println(ex);
}
finally{
if(rs!=null){
try{
rs.close();
}
catch(SQLException ex){}
}
if(stmt!=null){
try{
stmt.close();
}
catch(SQLException ex){}
}
if(conn!=null){
try{
conn.close();
}
catch(SQLException ex){}
}
}
It is just my suggestion i hope it can be a tip for you!
Best regards...
I failed to understand how preparedStatements should be used. In the end I decided not to use them and stick to executing a query string:
Map<String, String> personDetails = new Hashmap();
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select n.CODE, l.VALUE"
+ " from TNAME n join TPROPERTIES l on n.UIDPK = l.OBJECT_UID"
+ " where n.CODE IN (" + nameCodesString + ")")) {
while (rs.next()) {
nameCode = rs.getString(1);
displayName = rs.getString(2);
personDetails.put(nameCode, displayName);
}
}

please tell why control is not going to the pst.setString(1, userName); and next line control directly going to the elseif (more= true) 3rd line

See the control after the prepared statement going to the else if(more){} block
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
int k = pst.executeUpdate();
boolean more;
if(k > 0)
{
//boolean more = rs.next();
more = true;
}
else {
more = false;
}
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
String firstName = rs.getString("name");
String lastName = rs.getString("rollnumber");
System.out.println("Welcome " + firstName); `control coming here`
ex.setFirstName(firstName);
ex.setLastName(lastName);
ex.setValid(true);
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
The main problem is the use of int k = pst.executeUpdate();
Your query isn't an update statement, so it doesn't make sense to execute an update, it is likely that this will ALWAYS return 0, as no rows where updated.
Instead use executeQuery, which returns a ResultSet, which can use to determine if there are any rows matching your query, for example
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url,user,passsword)) {
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
try (ResultSet rs = pst.executeQuery()) {
if (rs.hasNext()) {
// Registered
} else {
// Unregistered
}
}
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
You may want to take a closer look at the JDBC(TM) Database Access trail

Inserting records into a MySQL table using Java

I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";

Categories

Resources