How to use IO with JDBC connection - java

this is my method for writing db query.
public static void post() throws Exception{
int clientMPNumber = Parcel.typeClientNumber();
int orderPassword = Parcel.generatePass();
try{
Connection con = ConnectionDB.getConnection();
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='77' AND `ClientPass`='1111';");
posted.executeUpdate();
}catch(Exception e){System.out.println(e);}
finally{
System.out.println("Insert completed");
}
}
I'm trying to do something like ATM machine. So I expect that user types his ID and password, and then the user can withdraw money or deposit money.
So I want to check login data correctness. User needs to type correct ID/password [logins/passwords are placed in MySQL DB].
PreparedStatement posted = con.prepareStatement("UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`='USER TYPES IT' AND `ClientPass`='USER TYPES IT';");
There is a sentence: "USER TYPES IT", this is my problem. I want to use here a Scanner or something like this. How can I do it?

A prototype for you (just an example, you should split up the part get userid, password, outside of this function for better practice):
public void post (){
Scanner sc = new Scanner(System.in);
System.out.println ("please enter user id:");
String userId = sc.nextLine();
System.out.println("please enter password:");
String pass = sc.nextLine();
Connection con;
PreparedStatement posted;
try {
con = ConnectionDB.getConnection();
String sql = "UPDATE `BankDB`.`Info` SET `Money`='77777' WHERE `ClientID`=? AND `ClientPass`=?";
posted = con.prepareStatement(sql);
posted.setString(1, userId);
posted.setString(2, pass);
posted.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
posted.close();
con.close();
}
}

Related

PrearedStatement executeUpdate() is not working

I'm new to JDBC and using the following code to update the row using MySQL JDBC driver. I have no idea why executeUpdate() is not updating the content in the database.
import java.sql.*;
import java.util.*;
public class UpdateDb {
UpdateDb() throws Exception,SQLException{
Scanner sc = new Scanner(System.in);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedb","root","");
String q="update table inserttbl set Name=?, City=? where id=?";
System.out.print("Enter new name to update: ");
String n = sc.nextLine();
System.out.print("Enter new city name to update: ");
String c = sc.nextLine();
System.out.print("Enter previous id: ");
int id = sc.nextInt();
PreparedStatement ps = conn.prepareStatement(q);
ps.setString(1, n);
ps.setString(2, c);
ps.setInt(3, id);
ps.executeUpdate();
System.out.print("updated");
conn.close();
}
public static void main(String[] arg) {
try {
UpdateDb up = new UpdateDb();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
Can anyone help me?
Your query string is wrong. It should be something like this:
String updateQuery = "UPDATE inserttbl SET Name=?, City=? WHERE id=?";
Look here for the proper syntax of update: https://www.mysqltutorial.org/mysql-jdbc-update
Also if you want to update then use an update table command. The command that you used for insert is wrong.
Also for error print out the exception that you logged.

SQLite database refuses to update and I'm not sure why

I'm using these two methods in order to update the balance of a bank app I'm writing, but the database refuses to update and I'm not sure why.
Function for getting how much to add:
public void addIncome(String cardNum,Scanner scanner){
System.out.println("Enter income: ");
int income = scanner.nextInt();
scanner.nextLine();
dataBase.addBalance(income,cardNum);
}
Prepared statement and function for query:
private final String ADD_BALANCE = ("UPDATE card SET balance=balance+? WHERE number=?");
public void addBalance(int amount, String number){
try (Connection con = this.dataSource.getConnection();
final var sql = con.prepareStatement(ADD_BALANCE)){
sql.setInt(1, amount);
sql.setString(2,number);
sql.executeUpdate();
}catch (SQLException throwables) {
throwables.printStackTrace();
}
}
You're missing a call to commit, meaning the transaction will implicitly rollback when the connection is closed (at the end of the try).
try (Connection con = this.dataSource.getConnection();
final var sql = con.prepareStatement(ADD_BALANCE)) {
sql.setInt(1, amount);
sql.setString(2, number);
sql.executeUpdate();
con.commit(); // HERE
}

"ORA-01008: not all variables bound"

I used this code for simple displaying data of any randomly selected id but this error is occurring I saw a various post about this error but I didn't any result for my program, please suggest me what is a problem.
I am using following code
public class Demo {
public static void main(String[] args) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:StudentInfo_Oracle","System","Aadi#123");
Scanner s = new Scanner(System.in);
String disq = "Select * from Sample where Id = ?";
System.out.println("Enter id number which data want to display: ");
int id = s.nextInt();
PreparedStatement dis = con.prepareStatement(disq);
dis.execute();
ResultSet rs = dis.getResultSet();
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
}
}
After PreparedStatement set value of ?
PreparedStatement dis = con.prepareStatement(disq);
dis.setInt(1,id);

JDBC - authorization users via database

I've made a program which is getting data from database and then authorizing, but the problem is only the last record is correct - logging in is succesful.
public class Test {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/uzytkownicy";
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.print("login: ");
Scanner zm1= new Scanner(System.in);
String name = zm1.next();
System.out.print("pass: ");
Scanner zm2 = new Scanner(System.in);
String password = zm2.next();
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting...");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
String sql = "SELECT logins, passwords FROM users";
ResultSet rs = stmt.executeQuery(sql);
String databasePassword = null;
String databaseUsername = null;
while (rs.next()) {
databaseUsername = rs.getString("logins");
databasePassword = rs.getString("passwords");
}
if (name.equals(databaseUsername) && password.equals(databasePassword)) {
System.out.println("Logged in!");
}
else {
System.out.println("Bad Pass/Login");
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
If I'm understanding what you're trying to do (which I may not be), your problem is that the comparison of username and password is outside the while loop, so your:
while (rs.next())
just loops through the entire result set, so when the while loop ends, databaseUsername and databasePassword will be set to the values from the last row read.
Instead, move the comparison inside the loop and set a flag (defaulting to false) and break out of the loop if the correct username and password is found, then use that flag to determine what to print.
Also, you might want to read up on parameterized queries. You can actually have the database do all the work for you by using a PreparedStatement and making your query:
SELECT 1 from users where logins = ? and passwords = ?;
If the result set contains anything, then the user entered a valid username and password, otherwise they didn't. The question marks in the query would be set to name and password using the set* methods of PreparedStatement.
Another note--storing plaintext passwords is a horrible idea. If the table storing the passwords is exposed (through various attacks or just a disgruntled employee stealing it), then everyone has all your users' passwords. Eek! You might argue that you'll take steps to prevent that, but from a security perspective, it's best to assume someday the table will be compromised, and do everything you can to ensure that it's not too harmful.

JDBC query + Scanner.next() gives InputMismatchException

I have written the simplest implementation of DBMS using Java's JDBC. In my app I gve users ability to perform CRUD operations on some simple mysql database. Everything done in console. Problem is that when users chooses operation from menu (queries currently hardcoded) and then provides query a java.util.InputMismatchException exception is thrown. Any ideas why this might be happening ? Here's the code:
import java.sql.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Base base = new Base();
boolean result = false;
try{
base.connect();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
int menuChoice = -1;
String query = "";
while(menuChoice != 0){
showMenu();
menuChoice = sc.nextInt();
System.out.println("Please provide your query : ");
switch(menuChoice){
case 1:
query = sc.next();
result = base.insert(query);
break;
case 2:
query = sc.next();
result = base.update(query);
break;
case 3:
query = sc.next();
result = base.retrieve(query);
break;
case 4:
query = sc.next();
result = base.delete(query);
break;
case 0:
System.out.println("Bye bye");
base.connection = null;
System.exit(0);
}
}
}
public static void showMenu(){
System.out.println("Welcome to simple JDBC example application./n");
System.out.println("Choose desired operation:\n\n");
System.out.println("1. Insert new instance");
System.out.println("2. Update existing instance");
System.out.println("3. Lookup");
System.out.println("4. Delete instance");
System.out.println("0. Exit");
System.out.print("\n\n Select: ");
}
}
class Base {
private String username = "";
private String password = "";
private String dbname = "";
private String servername = "";
private Statement stmt = null;
Connection connection = null;
public Base(){
}
public boolean create(){
return true;
}
public void connect() throws Exception{
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String url = "jdbc:mysql://" + servername + "/" + dbname;
connection = DriverManager.getConnection(url, username, password);
stmt = connection.createStatement();
}
public boolean insert(String statement){
try{
int i=stmt.executeUpdate(statement);
System.out.println("Successfully inserted.");
return true;
}catch(SQLException se){
System.out.println("Inserting data failed.");
return false;
}
}
public boolean update(String statement){
try{
int i=stmt.executeUpdate(statement);
System.out.println("Successfully updated.");
return true;
}catch(SQLException se){
System.out.println("Updating data failed.");
return false;
}
}
public boolean retrieve(String query){
try{
ResultSet rs = stmt.executeQuery(query);
System.out.println("Successfully retrieved :");
while (rs.next()){
System.out.println(rs.getRow()+". "+rs.toString());
}
return true;
}catch(SQLException se){
System.out.println("Updating data failed.");
return false;
}
}
public boolean delete(String statement){
try{
int i=stmt.executeUpdate(statement);
System.out.println("Successfully deleted.");
return true;
}catch(SQLException se){
System.out.println("Deleting data failed.");
return false;
}
}
}
/*
CREATE TABLE users (
user_login varchar(10) PRIMARY KEY NOT NULL,
user_password varchar(20) NOT NULL
);
CREATE TABLE groups (
group_id varchar(10) PRIMARY KEY NOT NULL,
group_name varchar(50),
group_description varchar(200)
);
CREATE TABLE groups_users (
user_login varchar(10),
group_id varchar(10),
FOREIGN KEY (user_login) REFERENCES users(user_login),
FOREIGN KEY (group_id) REFERENCES groups(group_id));
*/
EDIT: Traceback
Select: 1
Please provide your query :
SELECT * FROM users
Inserting data failed.
Welcome to simple JDBC example application./n
Choose desired operation:
Exception in thread "main" java.util.InputMismatchException
1. Insert new instance
at java.util.Scanner.throwFor(Scanner.java:840)
2. Update existing instance
at java.util.Scanner.next(Scanner.java:1461)
3. Lookup
at java.util.Scanner.nextInt(Scanner.java:2091)
4. Delete instance
0. Exit
at java.util.Scanner.nextInt(Scanner.java:2050)
at task.Main.main(Main.java:26)
Select: Java Result: 1
so error comes from line menuChoice = sc.nextInt();. What more, when I've added another scanner instance just for queries, picking operation type returns user back to the menu without asking for query.
Your Scanner breaks tokens on white space. Scanner.next() only returns one token (e.g. "SELECT"). The rest of your entered query is available for scanning for your nextInt() call, but the next token in your query (e.g. "*") is not an integer.
Instead of next() you probably want nextLine().
Here's the definition of InputMismatchException:
Thrown by a Scanner to indicate that
the token retrieved does not match the
pattern for the expected type, or that
the token is out of range for the
expected type.
I scanned through your code, and it seems like menuChoice = sc.nextInt(); might be the one that throws that exception. Chances are your while loop is looping too many times and your scanner doesn't have the next int value to read, which is the reason you get this exception.
nextInt() is the only Scanner API you used that throws this particular exception. Here's the documentation of nextInt():-
public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.
Parameters:
radix - the radix used to interpret the token as an int value
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
EDIT:
Try changing your while loop to be the following:-
while(menuChoice != 0 && sc.hasNext()){
...
}
This should fix your problem.

Categories

Resources