mySql connect to Java-debugging query - java

I have established a connection with mySql and Java and currently I can run a query from my database. I can run queries such as "Select * from Customer".
The problem appears, when i try to scan a value from the user and try to run it in my db.
select E.rent_id, name, telephone, Pa.date_get, Pr.date_return
from Rent as E, Customer as P, Get as Pa, return as Pr, Makes as Pg
where E.rent_id = Pg.rent_id
and Pg.cust_id = P.cust_id
and E.rent_id = Pa.rent_id
and E.rent_id = Pr.rent_id
and Month (Pa.date_get) = #input
and Year (Pa.date_get) = #input;
This is a query, which selects an id, a name, telephone, and dates of get and return of a vehicle (this is a db for a car rental company).
Unfortunately, when I connect to my db via Java, using the connector, I can't run this query.
Do you have any idea what to do?
Here follows the code in java that makes the connection and the use of the query, stated above.
package database;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connect {
public void databaseConnect(String connect_string, String username, String password) {
try {
Scanner scanner = new Scanner (System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connect_string, username, password);
System.out.println("Connection Succesful");
Statement statement = conn.createStatement();
System.out.println("Insert month: ");
int mina = scanner.nextInt();
System.out.println("Insert year: ");
int xrono = scanner.nextInt();
String query = "select E.rent_id, name, telephone, Pa.date_get, Pr.date_return\r\n" +
"from Rent as E, Customers P, Get as Pa, return as Pr, makes as Pg\r\n" +
"where E.rent_id = Pg.rent_id \r\n" +
"and Pg.cust_id = P.cust_id \r\n" +
"and E.rent_id = Pa.rent_id \r\n" +
"and E.rent_id = Pr.rent_id \r\n" +
"and Month (Pa.date_get) = #mina \r\n" +
"and Year (Pa.date_get) = #xrono;";
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Connect connectToServer = new Connect();
connectToServer.databaseConnect("jdbc:mysql://localhost/acr", "/*username*/", "/*password*/");
}
}
Can you see a mistake?
Thank you so much in advance!

Related

Access is denied when I am executing an update query with Ucanaccess

I have just started with ucanaccess and I am attempting to work out how it works. I wanted to update my Access database's username from "Sutaciba" to "Evan" but it shows the following error:
"Exception occured:
UCAExc:::4.0.4 C:\Users\evanc\AppData\Roaming\IT PAT DataBase (Access is denied)".
Seems like Ucanaccess doesn't have permission to gain access to my database for some reason.
Thank you for any help!
public static void main(String args[])
{
int ID = 1;
String username = "Sutachiba";
String password = "Evanchui123";
String email = "evanchui34#gmail.com";
try
{
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\evanc\\AppData\\Roaming\\IT PAT DataBase");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [username], [password] FROM [tblUser] WHERE ID =" + ID);
while(rs.next())
{
username = rs.getString(1);
password = rs.getString(2);
email = rs.getString(3);
System.out.println("Username: " + username + '\n' + "Password: " + '\n' + "Email:" + email);
}
String newN = "Evan";
String updateQuery = "UPDATE userDB SET (username) = (?) WHERE ID =" + ID;
PreparedStatement st = conn.prepareStatement(updateQuery);
st.setString(1, newN);
st.executeUpdate();
System.out.println("Successfully updated userdata!");
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception occured: ");
System.err.println(ex.getMessage());
}

check if value (Accountnumber) exist in a java database

I have the following method in a class called savings, am using JDBC database to save and view data on java application.
I have SAVINGS table in my database ZaiLab with the following fields,
ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)
and the following VALUEs will be entered by the user using JOPtionPane.
(id,accountNumber,customername,balance,minmum);
the application should then check if accountNumber entered by the user already exist, if not it should save the record to a table SAVINGS, if yes it should display the appropriate message. "Account already exist".
public void openSavingsAccount(int Id, int Amount) {
try {
String host = "jdbc:derby://localhost:1527/ZaiLab";
String uname = "siduduzo";
String upass = "Password01";
Connection con = DriverManager.getConnection(host, uname, upass);
Statement stmt = con.createStatement();
String SQL = "SELECT * FROM SAVINGS";
ResultSet rs = stmt.executeQuery(SQL);
int minmum = 1000;
balance = minmum;
while (rs.next()) {
int acc_col = rs.getInt("ACCOUNTNUMBER");
if (acc_col == accountNumber) {
JOptionPane.showMessageDialog(null, "Sorry, account " + accountNumber
+ " aready Exist");
} else if (Amount < minmum) {
JOptionPane.showMessageDialog(null, "Can not Open the Account, Minimum amount to deposit must be R1000");
} else {
balance = balance + Amount;
id = Id;
stmt.executeUpdate("INSERT INTO `SAVINGS`(ID,ACCOUNTNUMBER,CUSTOMERNAME,BALANCE,MINMUM)VALUE ('" + id + "','" + accountNumber + "','" + customername + "'," + balance + ",'" + minmum + "')");
}
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Right now you are selecting all rows from SAVINGS and attempt to insert a new account for each row that doesn't have the 'new' account number.
Instead, you should select only the row with the new account number, and insert when it doesn't exist.
You should also use prepared statements to protect you against SQL injection.
For example:
try (PreparedStatement checkAccountExists = con.prepareStatement(
"SELECT 1 FROM SAVINGS WHERE ACCOUNTNUMBER = ?")) {
checkAccountExists.setInt(1, accountNumber);
try (ResultSet rs = checkAccountExists.executeQuery()) {
if (rs.next()) {
// handle account already exists
} else {
try (PreparedStatement insert = con.prepareStatement(
"INSERT INTO SAVINGS(ID, ACCOUNTNUMBER, CUSTOMERNAME, BALANCE, MINMUM) VALUES (?, ?, ?, ? , ?)")) {
insert.setInt(1, id);
insert.setInt(2, accountNumber);
insert.setString(3, customername);
insert.setInt(4, balance);
insert.setInt(5, minmum);
insert.executeUpdate();
}
}
}
}
Alternatively, you could define a unique constraint on ACCOUNTNUMBER in your database and just do the insert and handle the constraint violation if the record already exists.

How to access a specific row in MySQL using Java

When I write a name as a user, I need to access the surname for this name which is already in database. For example:
Enter a name: beste
beste's surname is: ozcaglar
When I execute my code I can't see any surname as output.
In my database, I have name, surname and no (Auto-Incremented) columns.
import java.sql.*;
import java.util.*;
public class ConnectionMySQL {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String isim = scan.next();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/student","root","");
//System.out.println("Connection success");
String query= "SELECT surname FROM student_table WHERE name='isim'";
Statement stm =conn.createStatement();
ResultSet rs= stm.executeQuery(query);
while (rs.next()) {
System.out.println("Name: " + rs.getString("name")+ " Surname: "+rs.getString("surname"));
}
}
catch (Exception e) {
System.err.println(e);
}
}
}
You can follow this:
import java.sql.*;
import java.util.*;
public class test4 {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String isim = scan.next();
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
System.out.println("Connection success");
String query = "SELECT * FROM users WHERE surname='" + isim + "'";
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
String fName = rs.getString(1);
String sName = rs.getString(2);
System.out.println("Name: " + fName + " Surname: " + sName);
}
} catch (Exception e) {
System.err.println("Error");
}
}
}
The error means that the table doesn't have a column that is called "isim".
Maybe you meant to write:
SELECT surname FROM student_table WHERE name='isim'
?
EDIT (following the comments):
query = "SELECT surname FROM student_table WHERE name='" + isim + "'"
However this should not be used in a real-world application for security reasons (it allows SQL injection attacks).
In actual production code you should either escape input strings, or use parameterized queries...

Complications with auto commit switch

When I run my code, I just keep getting the error:
"ResultSet not open. Verify that autocommit is OFF."
How can I fix it?
I can't get it to work. I'm sure it has to do with con.setAutoCommint(false); or executeQuery.
package database_console;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static jdk.nashorn.internal.objects.NativeString.split;
import java.sql.*;
import java.sql.ResultSet;
import java.util.Random;
public class Database_console {
public static void main(String[] args) {
String url = "jdbc:derby://localhost:1527/English Words";
try {
String host = "jdbc:derby://localhost:1527/English Words";
String uName = "User";
String uPass= "password";
Connection con = DriverManager.getConnection(host, uName, uPass);
con.setAutoCommit(false);
Statement stmt = con.createStatement();
String SQL1 = "SELECT * FROM ENGLISH_1";
String SQL2 = "SELECT * FROM ENGLISH_2";
String SQL3 = "SELECT * FROM ENGLISH_3";
String SQL4 = "SELECT * FROM ENGLISH_4";
String SQL5 = "SELECT * FROM ENGLISH_5";
ResultSet rs1 = stmt.executeQuery( SQL1);
ResultSet rs2 = stmt.executeQuery( SQL2);
ResultSet rs3 = stmt.executeQuery( SQL3);
ResultSet rs4 = stmt.executeQuery( SQL4);
ResultSet rs5 = stmt.executeQuery( SQL5);
while(rs1.next()) {
String 1 = rs1.getString("1");
String 2 = rs2.getString("2");
String 3 = rs3.getString("3");
String 4 = rs4.getString("4");
String 5 = rs5.getString("5");
con.commit();
System.out.println( 1 + " " + 2 + " " + 3 " " + 4 " " 5 + " ");
}
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
Two things: First, COMMIT closes out transactions that start with BEGIN TRANSACTION. You don't have any of those.
Second, When you're using JDBC to execute SELECT statements, you need to execute each SQL statement, then retrieve and close its result set, before starting the next one. The code you showed tries to create a bunch of ResultSet objects and then read them one by one. You Can't Do That.™
Important: Don't forget to close() each ResultSet when you're done with it. ResultSets can be scarce resources on your database servers.
For example, try this.
String SQL1 = "SELECT col1, col2, col3 FROM ENGLISH_1";
String SQL2 = "SELECT col1, col2, col3 FROM ENGLISH_2";
Statement stmt = con.createStatement( );
ResultSet rs1 = stmt.executeQuery( SQL1 );
while(rs1.next()) {
String s1 = rs1.getString(1);
String s2 = rs1.getString(2);
String s3 = rs1.getString(3);
System.out.println( s1 + " " + s2 + " " + s3);
}
rs1.close();
ResultSet rs2 = stmt.executeQuery( SQL2 );
while(rs2.next()) {
String t1 = rs2.getString(1);
String t2 = rs2.getString(2);
String t3 = rs2.getString(3);
System.out.println( t1 + " " + t2 + " " + t3);
}
rs2.close();

How do I delete a row from database table in Java

I am trying to develop a simple Java DVD library console app in Java. I have created a database table that contains a list of DVD's. I have managed to get the adding a new DVD to the database functionally working, but I am struggling to delete a row from the database. When I use a SQL statement to select a row (row 7) then run the line 'rs.delete' I get the following exception:-
Invalid cursor state - no current row.
Below is my database table:-
ID Film Name Genre Rating
-------------------------------
1 Robocop Sci-fi 18
2 Terminator Sci-fi 18
3 Alien Sci-fi 18
4 Big Fish Fantasy PG
5 The Pianist Drama 18
6 Total Recall Sci-fi 18
7 Carnage Comedy 18
Below is copy of my code. Please could somebody help?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dvdlibrary;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import java.util.Scanner;
/**
*
* #author Andy
*/
public class DVDLibrary {
Connection con;
Statement stmt;
ResultSet rs;
String selection = "";
int id_num =0;
String film_name ="";
String genre ="";
String rating="";
public DVDLibrary()
{
DoConnect();
}
public void DoConnect() {
try
{
String host = "jdbc:derby://localhost:1527/DVDLibrary";
String username = "andyshort";
String password = "Pa55word";`enter code here`
con = DriverManager.getConnection(host, username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
/*
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
*/
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
public void GetUserInput()
{
System.out.println();
System.out.println("What would you like to do? Choose one of the following options.");
System.out.println("1. Display DVD library list");
System.out.println("2. Add a new film to database.");
System.out.println("3. Delete a film from the database.");
System.out.println();
Scanner user_option_selection = new Scanner(System.in);
selection = user_option_selection.next();
if(selection.equalsIgnoreCase("1"))
{
DisplayDVDList();
}
else if(selection.equalsIgnoreCase("2"))
{
AddRecord();
}
else if(selection.equalsIgnoreCase("3"))
{
DeleteRecord();
}
else
{
System.out.println("Incorrect option entered. Please try again.");
}
}
public void DisplayDVDList()
{
try
{
String SQL = "SELECT * FROM ANDYSHORT.DVDS";
rs = stmt.executeQuery(SQL);
System.out.println("ID Film Name Genre Rating");
System.out.println("-------------------------------");
while (rs.next())
{
int id_col = rs.getInt("ID");
String film_name_col = rs.getString("Film_Name");
String genre_col = rs.getString("Genre");
String rating_col = rs.getString("Rating");
String p = id_col + " " + film_name_col + " " + genre_col + " " + rating_col;
System.out.println(p);
//System.out.format("%32s%10d%16s", id_col , film_name_col, genre_col, rating_col);
}
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void AddRecord()
{
Scanner new_film_details = new Scanner(System.in);
System.out.println("Please enter film name: ");
film_name = new_film_details.next();
System.out.println("Please enter film genre: ");
genre = new_film_details.next();
System.out.println("Please enter film rating: ");
rating = new_film_details.next();
try
{
rs.last();
id_num = rs.getRow();
id_num = id_num + 1;
rs.moveToInsertRow();
rs.updateInt("ID", id_num);
rs.updateString("FILM_NAME", film_name);
rs.updateString("GENRE", genre);
rs.updateString("RATING", rating);
rs.insertRow();
//stmt.close( );
//rs.close( );
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
public void DeleteRecord()
{
String id = "";
Scanner id_of_film_to_delete= new Scanner(System.in);
System.out.println("Enter ID of film you want to delete.");
id = id_of_film_to_delete.next();
int idInt = Integer.parseInt(id);
try
{
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
rs = stmt.executeQuery(sql);
rs.deleteRow();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
GetUserInput();
}
}
use directly this query
"DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "+ idInt+");
int rowsDeleted = statement.executeUpdate();
if (rowsDeleted > 0) {
System.out.println(" delete successfully!");
}
Use prepared statements to avoid SQL injection:
PreparedStatement statement;
statement = con.prepareStatement("DELETE FROM andyshort.dvds WHERE id = ?");
statement.setInt(1, idToDelete);
statement.executeUpdate();
You can directly use delete query if you have the Id before hand.
String sql = "DELETE FROM ANDYSHORT.DVDS WHERE ID =" + idInt;
stmt.executeUpdate(sql);
But, it's better to use prepared statements instead of statements in order to avoid sql injection attacks.
String query= "DELETE FROM ANDYSHORT.DVDS WHERE ID = ? ";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1,idInt);
preparedStatement.executeUpdate();
You need to move the cursor to the first row before deleting the row, if you want to use deleteRow() method.
rs.first();
rs.deleteRow();

Categories

Resources