Mysql database multiple successive requests fail - java

All of my database access methods have been working up until now. I have a string of n usernames separated by ";", and I want to make n separate select statements to check if the user is online or offline. However, when used, this method returns nothing (""). The database connection is working. Any solutions are welcome.
EDIT:
New method, still does not work:
public static String CheckOn(String users) {
String toreturn = "";
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
try {
conn = Database.getDBConnection("test");
String sql = "SELECT name FROM sessions WHERE name=?";
stmt2 = conn.prepareStatement(sql);
String[] usarr = users.substring(1, users.length()).split(";");
for (int i = 0; i <usarr.length;i++){
if (usarr[i].equals("Empty")){
toreturn = toreturn + "-";
}
else{
stmt2.setString(1, usarr[i]);
rs2 = stmt2.executeQuery();
if (rs2.next()){
toreturn = toreturn + "y";
}
else{
toreturn = toreturn + "n";
}
rs2.close();
}
}
rs2.close();
stmt2.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} finally {
try {
if (stmt2 != null)
stmt2.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return toreturn;
}

Related

MySQL checking if something is already in a column

I am new to MySQL and don't really know how to check if in the column "friendCode" the same value already exist and if that's the case it should look if in the same row in the "watched" column the value "0" is. I have already managed to check whether the code exists in a row. I just don't know how to look for the second condition.
Here is a picture how the table looks like:
And here that what I already managed to do:
public static boolean checkRow(String query) {
boolean ret = false;
try (Connection con = DriverManager.getConnection(url, user, password)) {
Statement stmt = con.createStatement();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next() && !rs.getString("watched").equals(0)) {
ret = false;
} else {
ret = true;
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return ret;
}
I think you are not written any select query in this program. If you are calling from the main method just check and try the below steps.
In Given Table watched column have integer DataType data.
Your Compare to String type.
Try it my code it's working if you have any concern revert back to this comment.
public static boolean checkRow(String query) {
boolean ret = false;
try (Connection con = DriverManager.getConnection(url, user, password)) {
Statement stmt = con.createStatement();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next() && rs.getString("watched")!=0) {
ret = false;
} else {
ret = true;
}
rs.close();
stmt.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return ret;
}

How to deal with multiple queries in a java servlet

I'm trying to send an increase count variable of a picture (which is increased by just increasing +1 everytime a new session hits a picture). I'm getting the following error message however, i'm checking for an empty result set. My thought process is that I can try to select the picturesNo that has been called and if it can't find that pictureNo we simply insert the first count to the table, and if it can find it, we then update this.
Error message:
"SQLException: Illegal operation on empty result set."
Code to increase the count for the session
HttpSession session = request.getSession() ;
Integer counter = (Integer) session.getAttribute("counter");
String accCount = (String) session.getAttribute("attributeKey") ;
String url = "http://localhost:8080/techfore";
String encodedURL = url + ";jsessionid=" + request.getSession().getId();
if (accCount == null || encodedURL == null) { // New session?
response.sendRedirect("/techfore/WelcomePage");
}
else{
if(counter == 0) {
counter = new Integer(counter.intValue() + 1);
session.setAttribute("counter", counter);
}
}
Utilities.initalCount(out, pictureName, counter);
Code to run the queries
public static void initalCount(PrintWriter out, String pictureName, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
}
try {
Statement stmt = con.createStatement();
String query0;
ResultSet rs1;
query0="SELECT PictureNo FROM Statistics WHERE PictureNo = (SELECT PictureNo FROM Pictures WHERE ShortName = '"+pictureName+"')";
rs1 = stmt.executeQuery(query0);
if(rs1.next()){
//yes exist
String description = rs1.getString("Description");
int pictureNo = rs1.getInt("PictureNo");
IncreaseCount(out, pictureNo, accessCount);
}
else {
//if rs is null insert
int pictureNo = rs1.getInt("PictureNo");
AddCount(out, pictureNo, accessCount);
}
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void AddCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="INSERT INTO Statistics VALUES "+pictureNo+","+accessCount+" ";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void IncreaseCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="UPDATE Statistics SET AccessCount = "+accessCount+" + 1 WHERE PictureNo = "+pictureNo+"";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
New insert
query="INSERT INTO Statistics VALUES (SELECT PictureNo FROM Pictures WHERE FileName = '"+pictureName+"'),"+accessCount+" ";

How to insert values from csv into database in java

I have tried the following code to split the csv values and now how do insert it in to DB? Do I have save the values in to separate variables to match column names? I am unable to figure out.
Note: I don't want to use any csv parser right now. I just want to do it manually
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
String name;
String email;
String phone;
String ID;
Connection con = OracleDBConnection.getConnection();
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement st = con.prepareStatement();
st.executeUpdate(query);
try {
BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));
while (bReader != null) {
String read;
try {
read = bReader.readLine();
if (read != null)
{
String[] array = read.split(",+");
for(String result:array)
{
System.out.println(result);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
if (bReader == null)
{
bReader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
output:
1Kiriti
kiriti#gmail.com
880789939
Column names in Database:
Name Email Phone ID
Use Parepared statement and build a query in while Loop and execute it. For more on Prepared Statement please check Check this link
String sql = " INSERT INTO TABLE_(name,email,phone,id) VALUES(?,?,?,?) ";
try {
BufferedReader bReader = new BufferedReader(new FileReader("1000rows.csv"));
String line = "";
while ((line = bReader.readLine()) != null) {
try {
if (line != null)
{
String[] array = line.split(",+");
for(String result:array)
{
System.out.println(result);
//Create preparedStatement here and set them and excute them
PreparedStatement ps = yourConnecionObject.createPreparedStatement(sql);
ps.setString(1,str[0]);
ps.setString(2,str[1]);
ps.setString(3,str[2]);
ps.setString(4,strp[3])
ps.excuteUpdate();
ps. close()
//Assuming that your line from file after split will folllow that sequence
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
finally
{
if (bReader == null)
{
bReader.close();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
You can use Prepare Statement and set the value in parameter at each iteration:
Connection con = OracleDBConnection.getConnection();
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement ps=con.prepareStatement(query);
ps.setString(1,array[0]);
ps.setString(2,array[1]); // and so on
ps.executeUpdate();
If No of Rows are more you can also use Batch Processing :
String sql = "Insert into NEWSTUDENT values(?,?,?)";
PreparedStatement preparedStatement = null;
try{
preparedStatement =
connection.prepareStatement(sql);
preparedStatement.setString(1, "Gary");
preparedStatement.setString(2, "Larson");
preparedStatement.setString (3, "Test");
preparedStatement.addBatch();
preparedStatement.setString(1, "Stan");
preparedStatement.setString(2, "Lee");
preparedStatement.setString (3, 456);
preparedStatement.addBatch();
int[] affectedRecords = preparedStatement.executeBatch();
}finally {
if(preparedStatement != null) {
preparedStatement.close();
}
}
You can store your data in an array and bind them to your statement:
String query = "Insert into NEWSTUDENT values(?,?,?,?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,array [0]);
st.setString(2,array[1]);
....
st.executeUpdate();
For more informations about prepared statements see the oracle documentation

jdbc sqlite returns no rows

public ArrayList<Booking> getAllBookings(){
ArrayList<Booking> list = new ArrayList<Booking>();
int rowCount = 0;
try {
stmt = connection.createStatement();
String sql = "SELECT * FROM Bookings";
ResultSet rows = stmt.executeQuery(sql);
rows.last();
System.out.println("Row Count "+rows.getRow());
rows.beforeFirst();
connection.commit();
while (rows.next()){
Booking b = new Booking();
otherStuff();
list.add(b);
rowCount++;
}
stmt.close();
rows.close();
} catch (Exception e) {
}
System.out.println("There were " +rowCount + " records.");
return list;
}
Why do I not get any rows returned? I am connecting using this:
public static Connection dbConnect(){
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:D:/test/test_db.sqlite3");
System.out.println("Connection Succesful");
return connection;
} catch (Exception e) {
System.out.println(e);
return null;
} }
When running SQLite Studio my query returns the correct results, but here my output on console is:
Connection Succesful
(Row Count + rows.getRow() is not printing here for some reason)
There were 0 records.

Inserting information from one mysql table to another

I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;

Categories

Resources