Why does my query works only for number<10? - java

I use this func when entering data. So I need to check is there an employee with this id in db. The same function I use for registration and this method works. But when it comes to integer numbers it checks only when it's under 10 (or maybe it's the first inserted value)
This is my code to check unique of id:
private int checkUnique() {
try {
Scanner scan = new Scanner(System.in);
id = scan.nextInt();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:...", "...", "...");
Statement st = connection.createStatement();
ResultSet res = st.executeQuery("select id_emp from employees");
while (res.next()) {
if (res.getInt("id_emp")==getId()) {
res.close();
st.close();
connection.close();
System.out.println("There is employee with this id");
System.out.println("Enter id");
checkUnique();
} else {
res.close();
st.close();
connection.close();
return id;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
And that how I use it in my code:
Statement st = connection.createStatement();
String sql = "INSERT INTO employees (id_emp, first_name, last_name, cnt_kids, cnt_dkids,is_single,added_by) " +
"VALUES (?, ?, ?, ?, ?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
System.out.println("Enter id");
id = checkUnique();
What's wrong with this?
For example this code ask to enter other id when id=2(it's realy on the table), but when I insert id=12(also in the table) it just skips.
My table:
CREATE TABLE `employees` (
`id_emp` int NOT NULL,
`first_name` varchar(30) DEFAULT NULL,
`last_name` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
`cnt_kids` int DEFAULT NULL,
`cnt_dkids` int DEFAULT NULL,
`is_single` bit(1) DEFAULT NULL,
`added_by` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL,
PRIMARY KEY (`id_emp`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Use a prepared statement
Here is some sample code:
public class SQLMain {
public static void main(String[] args) throws SQLException {
System.out.println("ID to check:");
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test");
PreparedStatement preparedStatement = connection.prepareStatement("select id_emp from employees where id_emp = ?");
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
// we have a row
System.out.println("Found employee with id of: " + resultSet.getInt(1));
} else {
// no row found - therefore unique
System.out.println("not found");
}
resultSet.close();
preparedStatement.close();
connection.close();
scanner.close();
}
}

Related

get exeption when try to update foreign key

im learning now mysql and jdbc and i got home work im trying to add a foreign key and i cant understant what is this exeption this is my code please if someone can explain me what the problem it will realy help me
package jdbc;
import java.sql.*;
public class JDBC_HW {
public static void main(String[] args) throws ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/newdatabase", "root", "admin")) {
try (Statement statement = connection.createStatement()) {
String newTable = "CREATE TABLE jb_student (id int not null auto_increment, name varchar(500), grade int, PRIMARY key(id));";
statement.executeUpdate(newTable);
}
String insertStudents = "INSERT INTO newdatabase.jb_student "
+ "( name, grade)"
+ " VALUES( ?, ?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertStudents)) {
for (int i = 0; i < 100; i++) {
preparedStatement.setString(1, "student" + i);
preparedStatement.setInt(2, i * 100);
preparedStatement.executeUpdate();
}
}
String printTable = "select * from newdatabase.jb_student";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(printTable);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String update = "UPDATE jb_student SET name = 'nikita', grade = 100 where id = 1;";
try (Statement statement = connection.createStatement()) {
int countUpdates = statement.executeUpdate(update);
System.out.println("updated rows : " + countUpdates);
}
String searchByName1 = "select * from jb_student where name like '%1';";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(searchByName1);
while (resultSet.next()) {
System.out.print(resultSet.getInt(1));
System.out.print(" ");
System.out.print(resultSet.getString(2));
System.out.print(" ");
System.out.println(resultSet.getInt(3));
}
}
String newTable = "CREATE TABLE jb_courses (id int not null auto_increment, name varchar(500), PRIMARY key(id));";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(newTable);
}
String insertCourses = "INSERT INTO newdatabase.jb_courses "
+ "(name)"
+ " VALUES(?);";
try (PreparedStatement preparedStatement = connection.prepareStatement(insertCourses)) {
for (int i = 0; i < 5; i++) {
preparedStatement.setString(1, "course" + " " + i);
preparedStatement.executeUpdate();
}
}
String addColumn = "ALTER TABLE jb_student ADD COLUMN course_id int not null AFTER id;";
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(addColumn);
}
String addFk = "ALTER TABLE jb_student add FOREIGN KEY (course_id) REFERENCES jb_courses (id);";
try(Statement statement = connection.createStatement()){
statement.executeUpdate(addFk);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
im sitting on this long time and cant resolve this exeption i tryied everithing i could think of
and im still getting this exeption :
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`newdatabase`.`#sql-12f0_21`, CONSTRAINT `jb_student_ibfk_1` FOREIGN KEY (`course_id`) REFERENCES `jb_courses` (`id`))
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1333)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2106)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1243)
at jdbc.JDBC_HW.main(JDBC_HW.java:92)
im braking my head on this thank you for helping

update database based on user input in java

i'm a new programmer, I was given a task to create a class Subject.java, in which it'll ask the students how many subjects they're taking and then store the subjects information into the database, but the problem with my current code is that only one row is updated in the database. My code is as the following, please help me.
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i=0;
for (i=0; i<sub; i++)
{
System.out.print("\nCode: ");
this.setCode(in.next());
System.out.print("\nName: ");
this.setName(in.next());
System.out.print("\nCredit: ");
this.setCredit(in.nextInt());
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
try (Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);)
{
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt (3, this.getCredit());
pstmt.addBatch();
if (pstmt.executeUpdate() == 1)
{
System.out.println("\nNew subject has been created succesfully!");
}
else
{
System.out.println("\nError");
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
As Nexevis said , you need to put your Connection code outside your for-loop like below :
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i = 0;
try {
Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);
for (i = 0; i < sub; i++) {
System.out.print("\nCode: ");
this.setCode( in.next());
System.out.print("\nName: ");
this.setName( in.next());
System.out.print("\nCredit: ");
this.setCredit( in.nextInt());
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt(3, this.getCredit());
pstmt.addBatch();
}
try {
// execute it to insert the data
pstmt.executeBatch();
} catch (SQLException e) {
System.out.println("Error message: " + e.getMessage());
return; // Exit if there was an error
}
pstmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}

SQL injections (java)

I am trying to figure out a way to see if the sql injection is correct based on the user input and if so, delete that row.
For instance the user enters 123 for an idNumber, if that number exits, the the sql statement "select * from student where idNumber = " + idNumber + ";" would be correct.
When it is verified that it is correct, I would then use another statement to delete the query.
My main issue is figuring out how to verify it is correct.
Thanks!
public static void CheckStudent(Connection con, String idNumber) throws SQLException {
Statement stmt = null;
String query = "select * from student where idNumber = " + idNumber + ";"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (!rs.isBeforeFirst() ) {
//Here is where you do the check
System.out.println("No data");
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

Exhausted ResultSet Issue with Servlet Oracle

Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}

sql.exception: column not found

Hi guys can u tell me what is wrong with my code?
When I set my ResultSet as "SELECT * FROM Table1" it works perfectly,
also if it is "SELECT key, itemName, itemPrice, itemQuantity FROM Table1"
but when I try to use only one of them or two it prints out an error column not found.
My database is stored in MS Acceess. That's my main:
try (Connection cn = DBUtil.getConnection(DBType.MS_ACCESS);
Statement st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT Table1.key FROM Table1");) {
Table1.displayData(rs);
} catch (SQLException ex) {
DBUtil.processException(ex);
}
and that's Table1.java:
public class Table1 {
public static void displayData(ResultSet rs) throws SQLException {
// to print out my database
while (rs.next()) {
StringBuffer buffer = new StringBuffer();
buffer.append(rs.getString("key") + " ");
buffer.append(rs.getString("itemName") + " ");
double price = rs.getDouble("itemPrice");
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
String formattedPrice = pounds.format(price);
buffer.append(formattedPrice + " ");
buffer.append(rs.getInt("itemQuantity") + " ");
System.out.println(buffer.toString());
}
}
}
Your result set will only contain the columns that you define in your select query. So if you do
rs.getString("itemName")
then you have to select that column in your query, which you don't
st.executeQuery("SELECT Table1.key FROM Table1")
^-----------------column missing
Do
st.executeQuery("select key, itemName, itemPrice, itemQuantity from Table1")
you should use
buffer.append(rs.getString("Table1.key") + " ");
resultset have the data with name which you have given in select query.(key=Table1.key)

Categories