Java SQL Insert Multiple variables - java

i'm working at my uni project and i have to make a classbook for a local school.My problem is that i want to insert multiple grades into the grades field.I've tought about making an integer array of the jtestfield.getText() and then converting it to a string so i can insert it into table.
PreparedStatement ps = con.prepareStatement(
"UPDATE elev SET fizica=? WHERE nume=? AND prenume=?");
// nota1=Integer.parseInt(nota.getText());
// ps.setInt(1, nota1);
String sir=nota.getText();
int[] result = Arrays.stream(sir.split(","))
.mapToInt(Integer::parseInt).toArray();
String note=Arrays.toString(result).replaceAll("\\[|\\]|,|\\s", "");
ps.setString(1,note);
ps.setString(2,text.getText());
ps.setString(3, text1.getText());
ps.executeUpdate();
This is the portion of the code but i keep getting java.lang.NullPointerException.

I've tought about making an integer array...
Don't.
The simplest solution is to use a 1:n relationship between the table elev and a new one score. Then you can store many scores in the second table.

Related

Java how to increase the value of doubles in a database table

I am having some trouble figuring out a query that will update values in a column in one of my tables. Below is my function:
public void increasePrice(String [] str) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("Update Journey Set price+=? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);
ps.setDouble(1,Double.parseDouble(str[1]));
ps.setDouble(2, Double.parseDouble(str[0]));
ps.executeUpdate();
ps.close();
System.out.println("1 rows updated.");
} catch (SQLException ex) {
Logger.getLogger(Jdbc.class.getName()).log(Level.SEVERE, null, ex);
}
}
To illustrate, the array passed in contains a value for distance and price and I am wanting to update the prices in the 'Journey' table based on their distance. For example, if a record in the table has a distance (type double) that is less than a given distance (the value of str[0]), I want to increase the price (also a double) of that record by the value 'str[1]' and do this for all records in the table.
The above code doesn't give any errors however, the records in the database never get updated. I could really use some help with this as I've searched around for a while now to try and find a solution and have not yet succeeded.
I do not know what database you are using but my guess is that this line:
ps = connection.prepareStatement("Update Journey Set price+=? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);
should be written like this:
ps = connection.prepareStatement("Update Journey Set price=price+? where distance <?",PreparedStatement.RETURN_GENERATED_KEYS);
And not related to your question but the line
System.out.println("1 rows updated.");
may make you waste hours of debugging in the future because 0 or more rows can be actually updated.

My java program isn't counting database rows correctly

I'm making a program and I have to get the number of rows in a MySQL database. My table has 4 rows but for some reason I'm getting the number 1 everytime I run the program. Here is my code:
public static void showItems() throws Exception {
try{
Connection con = getConnection();
Statement search = con.createStatement();
ResultSet rs = search.executeQuery("SELECT COUNT(id) FROM main;");
int rows = 0;
rs.beforeFirst();
while (rs.next()){
rows++;
}
System.out.println(rows);
Can someone help me? What am I doing wrong here?
I tried many different ways and none returns me the correct value.
Thanks in advance!
Your query returns one row and contains the value 4 (the count of the number of rows in the table).
Run your query directly in a database client and look at what you get.
This bit of code should show you how to get ahold of the "4". Try this loop in place of the one that contains "row++":
while (rs.next()) {
System.out.println(rs.getInt(1));
}

Generate Random & Unique Number and Insert into Database

My goal is to generate random number and insert into database. I do not want any duplication. I have done my research, one of is to check at database first, and then insert.
//GENEREATE RANDOM NUMBER
long number = (long) Math.floor(Math.random() * 900000L) + 900000L;
//CHECK IF NUMBER IS ALREADY EXIST IN DATABASE
String searchQuery = "select appleId from food where appleId='" + number + "'";
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(searchQuery);
boolean appleIdExists = rs.next();
//IT IS UNIQUE
if (!appleIdExists) {
try {
//INSERT STATEMENT
.......
} catch (SQLException e) {
e.printStackTrace();
}
}
//IT IS NOT UNIQUE..
else
{
.....
}
}catch (Exception ex) {
System.out
.println("Log In failed: An Exception has occurred! "
+ ex);
}
So my problem is if it NOT unique, I need to generate another number and check again? And check again and again until it is unique? Will the result be many if-else statement?
I am not sure if use if-else statement is the efficient way. Or there is another way?
Any suggestion?
Help will be appreciate! :)
Why not use an auto incrementing identity column in the database, essentially making the database create a unique id for you? Every modern DBMS supports this capability.
For MySQL:
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
)
For PostgreSQL:
CREATE TABLE animals
(
id serial primary key,
name VARCHAR(40) not null
);
All databases have this capability, and when you use JDBC to insert a row, you get back the key of the inserted row in the response. A simplified example:
String query = "INSERT INTO animals (name) VALUES ('zebra')";
Integer insertedId = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
If all you want to do is generate random numbers and insert into database, then you can use Fisher Yates shuffle algorithm
Check this question for details: Unique (non-repeating) random numbers in O(1)?
You can hold the random numbers (generated/existing) to a collection/or cache or queue. don't need to check every time in DB.
Try to do the operations in batch. either first generate all the unique random numbers and the persist based on your requirement.
Define an Unique ID on the column - don't need to do a select and insert, just do a INSERT in case of failure repeat the same process.
You can use recursion as we don't know the failure's count.
theexamtime.com

Trying to pass a Java variable into a sql string

I've had a look around on the web but can't seem to find a definite answer to my question.
Basically, I have a database and table that are successfully working. Now I want to read each line from my table one by one and store the result into a array and I am trying to use a for loop to be more professional rather then using repetition.
I have this code
for (int i=1; i<=8; i++)
{
String query = "Select * FROM Table1 WHERE ID = i";
Rs = St.executeQuery(query);
COL1Title[i] = Rs.getString("CO1Name");
COL2Age[i] = Rs.getString("CO2Rating");
}
The for loop is in a try catch statement and it's complaining with the error "Unknown column 'i' in 'where clause'"
Im guessing there's a certain way for how variable i is to be inserted in the the query.
I should point out ID is a column that has the auto increment feature added on and is primary key if that helps
Could anyone help me out here?
First, we can simplify the task be executing a single query. Note the addition of the range limit and the ORDER BY - without an ORDER BY the results have an unspecified order!
PreparedStatement stmt = "Select ID, CO1Name, CO2Rating"
+ " FROM Table1"
+ " WHERE ID >= ? AND ID <= ?"
+ " ORDER BY ID";
And bind in placeholders (unless there is good reason otherwise, always use placeholders when injecting data into a query). The values could have been hard-coded above in this case, just as they are hard-coded in the for-loop, but the binding is shown here for future reference:
stmt.setInt(1, 1);
stmt.setInt(2, 8);
Then execute the query:
ResultSet rs = stmt.executeQuery();
And iterate the results. Note that rs.next() must be invoke once before any column is read (the cursor starts before any records) and, in this case, it makes it easy to handle a bunch of results.
while (rs.next()) {
int id = rs.getInt("ID");
String title = rs.getString("CO1Name");
String name = rs.getString("CO2Rating");
// do stuff with this record
}
Note that even though the ORDER BY guarantees that the results are iterated in order of ID, assuming a database cardinality rule ensures each result has a unique ID, there may be 0 to 8 records returned - that is, non-existent records may need to be detected/handled separately.
Also (but not shown), make sure to cleanup (close) the ResultSet when done: use a try/finally or try-with-resources construct.
You need to pass i in string as integer, Replace line by:
String query = String.format("Select * FROM Table1 WHERE ID = %d",i);

java, mysql compare and edit values

I`m building a decision support system in java. Below is a part of code, that scans the search word that is typed in by user, then compares it with database searchlog.searchcolumn values and if the word is not there creates a new entry. BUT in the if statement i want it to check for the entry, and if it IS already in searchlog.searchcolumn column, then I want it NOT to create a new duplicate entry, but to add +1 value to searchlog.counter column for the specific word.
for example if search word is "UMBRELLA" and there is already one entry for umbrella in database, i want it to add +1 to counter column in UMBRELLA row.
the purpose of this, is to store all searchwords and keep a track of the most popular ones.
Thank you for your time
String CheckSearch = "SELECTsearchcolumn FROMsearchlog";
String InsertColumn = "INSERT INTO `mydb`.`searchlog` (`searchcolumn`) VALUES ('"+ InputScanner + "');
//
if (InputScanner.equals(CheckSearch))
System.out.println("value ealready exist, counter well be updated");
else
stmt.executeUpdate(InsertColumn);
EDIT
Thank you for advice of using PreparedStatement, but this is my first more or less serious challenge and for this time, let`s just ignore vulnerability of my code. Thanks
What database are you using? If you are using MySQL, then you should look into INSERT ... ON DUPLICATE KEY UPDATE statement. (Other SQL databases have MERGE, which I'm less familiar with.) Here is the MySQL Documentation.
You will need make your searchcolumn a UNIQUE or PRIMARY column, then something along the lines of: INSERT INTO searchlog (searchcolumn, count) VALUES ("my search query", 0) ON DUPLICATE KEY UPDATE count = count + 1; will accomplish what you want.
your query should be :
String InsertColumn = "INSERT INTO `mydb`.`searchlog` (`searchcolumn`) VALUES ('"+ InputScanner + "'");
Values clause should also be wrapped around brackets.
and always use equals() to check if two strings are meaningfully equal. In case of objects == checks if two reference variables refer to the same object.
if (InputScanner == CheckSearch) {
should be:
if (InputScanner.equals(CheckSearch)) {
Then, your if statement would return true if InputScanner is same as checkSearch.
ADVICE:
I strongly recommend you to use PreparedStatement rather than simple Statement to prevent SQL Injection.
PreparedStatement st = conn.preparedStatement(InsertColumn);
st.setString(1, val1);
1) Values also need to be in braces
Example:
VALUES ('"+ InputScanner + "');
2) Assuming InputScanner and CheckSearch are Strings/comparable objects, you need to do .equals() instead of ==
Example:
if (InputScanner.equals(CheckSearch)) {
Note: Your SQL statement is prone to SQL Injection attack. Better to use PreparedStatement.
There is an MySQL statement for your task:
Requierement: searchcolumn is a unique key.
String sql = "INSERT INTO mydb.searchlog(searchcolumn, counter) VALUES(?, 1) "
+ " ON DUPLICATE KEY UPDATE counter = counter + 1";
PreparedStatement stmt = connection.createPreparedStatement(sql);
stmt.setParameter(1, checkSearch.toUpperCase());
int updateCount = stmt.executeUpdate();
I do not know whether updateCount distinghuishes whether an INSERT or UPDATE happened though. You could use getGeneratedKeys for that purpose, if there is a unmentioned AUTOINCR primary key.

Categories

Resources