I'm confused, I was asked to do a connection from Java into MySQL using OOP and DAO, but my professor asked us to do it in a the following way:
We need to make the variable "MethodOfPayment" as an int in Java and as a char in MySQL table, and we need to write the method of payment depending on the number you put in Java. For example:
Java: MethodOfPayment: (you write) 1 will insert "Credit card" in MySQL
Java: MethodOfPayment: (you write) 2 will insert "Debit card" in MySQL
but using the int MethodOfPayment variable.
I tried a switch, but it won't let me convert the int "With" letters to string, I don't even know if it's possible.
This is the insert I have in the DAO method class
private static final String SQL_INSERT = "INSERT INTO Client(Name, LastName, MethodOfPayment ) VALUES (?,?,?)";
I do it with ResultSet, ArrayList, PreparedStatement with a JDBC connection to MySQL.
public static int = MethodOfPayment;
This is the variable that will write on the database an the one my professor is asking us to keep as an int in java and write the char on MySQL.
This is the method I'm trying to convert the int to string, but obviously crashes because the letters inside the int. I don't know if it's possible or my professor is wrong.
public static void PaymentMethod() {
int MethodSelection; //this is a variable to select the method in the switch and assign the values to the main variable of the payment
System.out.println("Insert Payment Method");
Scanner sc = new Scanner(System.in);
MethodSelection = Integer.parseInt(sc.nextLine());
switch (MethodSelection) {
case 1:
MethodOfPayment = Integer.parseInt("Debit");
break;
case 2:
MethodOfPayment = Integer.parseInt("Credit Card");
break;// ...
default:
System.out.println("Invalid Method, Try Again");
PaymentMethod(); // I don't know a way to restart the switch without restarting the whole method when another value is inserted
}
}
DAOmethod:
Person is the father clas with, name and Last name. I get TypeOfPayment from a son class that has get, set and stringbuilder with the super to get the person data
public int insert(Client person){
Connection conn = null;
PreparedStatement stmt = null;
int registros = 0;
try {
conn = getConnection();
stmt = conn.prepareStatement(SQL_INSERT);
stmt.setString(1, person.getStr_Name());
stmt.setString(2, person.getStr_Lastname);
stmt.setInt(3, person.getInt_TypeOfPayment());
archives= stmt.executeUpdate();
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}finally{
try {
close(stmt);
close(conn);
} catch (SQLException ex) {
}
}
return archives;
}
There are multiple ways to achieve this.
if you are using Hibernate you can do it with #Type annotation
If you are using JPA then you can do it with convert. It is simpler among all.
If you are using simple JDBC and not using entity mapping, then while saving before executing query set parameters as debit, credit based on number entered by user. For example:
stmt.setString(3, person.getInt_TypeOfPayment() == 2 ? "debit" : "credit" );
While retrieving data, iterate over result set and set value as int based on the string which comes from data base. Sample code as follows.
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
....
int payment = rs.getString("your column name / index") == "debit" ? 2 : 1;
person.setIntTypeOfPayment(payment);
}
I have modified your program. Java naming conventions for variable is lowerCamelCase, happy learning!
package test1;
import java.util.Scanner;
public class Snippet {
public static void PaymentMethod() {
int methodSelectionInt;// this is a variable to select the method in the swich and asign the values to
// the main variable of the payment
String methodOfPayment;// the database variable of the payment
Boolean tryAgain = false;
while (tryAgain) {
System.out.println("Insert Payment Method");
Scanner sc = new Scanner(System.in);
methodSelectionInt = Integer.parseInt(sc.nextLine());
switch (methodSelectionInt) {
case 1:
methodOfPayment = "Debit";
tryAgain = false;
break;
case 2:
methodOfPayment = "Credit Card";
tryAgain = false;
break;// ...
default:
System.out.println("Invalid Method, Try Again");
tryAgain = true; //
}
}
}
}
If you need to convert char to int in Java use one of the methods:
Implicit type casting //getting ASCII values
Character.getNumericValue()
Integer.parseInt() //in pair with
Subtracting ‘0’ //works for integer numeric values only
You can also do explicit type casting. However, this is a redundant operation: it is not needed, but just works in Java.
you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
public static void PaymentMethod() {
int MethodSelection;//this is a variable to select the method in the swich and asign the values to the main variable of the payment
System.out.println("Insert Payment Method");
Scanner sc = new Scanner(System.in);
MethodSelection = Integer.parseInt(sc.nextLine());
switch (MethodSelection) {
case 1:
MethodOfPayment = Optional.ofNullable("Debit").map(Ints::tryParse).orElse(0);
break;
case 2:
MethodOfPayment = Optional.ofNullable("Credit Card").map(Ints::tryParse).orElse(0);
break;
default:
System.out.println("Invalid Method, Try Again");
PaymentMethod();
}
}
Consider using concatenation (" string " + variable + " string "), or using a StringBuilder. https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Related
I have written the following code and the resultset (here its labelled as rs3) is returning true even though there is no result.I want to check if there is no result then the user has to enter correct phone manufacturer again.Don't know where I am going wrong?
BufferedReader r2 = new BufferedReader(new InputStreamReader(System.in));
String phone_manufacturer="";
boolean value1=true;
while (value1) {
System.out.println("\nPlease select your choice of phone manufacturer " );
String line = r2.readLine();
if (line.matches("[A-Za-z ]+$")) {
phone_manufacturer = line;
final String sql3 = "SELECT * from phone_model WHERE phone_type = '"+phone_type_choice+"' and manufacturer ='"+phone_manufacturer+"'";
st3 = connection.createStatement();
rs3= st3.executeQuery(sql3);
if(rs3!=null){
System.out.println("Model"+" "+"Manufacturer"+""+"Phone_type");
while(rs3.next()){
String modell = rs3.getString("Model");
String manufacturer = rs3.getString("Manufacturer");
String phone_type = rs3.getString("Phone_type");
System.out.format("%-25s%-20s%-10s\n",modell,manufacturer,phone_type);
}
}
else
{
System.out.println("The manufacturer isn't avaiable for the phone type choosen.Please try again");
value1=true;
continue;
}
value1=false;
}else
{
System.out.println("\nPlease enter correct manufacturer name " );
value1=true;
continue;
}
break;
}
Use :
if (!rs3.next() ) {
System.out.println("no data");
}
initially the ResultSet's cursor is pointing to before the first row, if the first call to next() returns false then there was no data in the ResultSet.
if you are working with a newly returned ResultSet whose cursor is pointing before the first row, an easier way to check this is to just call isBeforeFirst().
if (!rs3.isBeforeFirst() ) {
System.out.println("No data");
}
it's better to use prepared statment to avoid sql injection :
PreparedStatement updateemp = connnection.prepareStatement
("SELECT * from phone_model WHERE phone_type =? and manufacturer=?");
updateemp.setString(1,phone_type_choice);
updateemp.setString(2, phone_manufacturer);
How To use prepared statement.
i am trying to an integer field from the product table and trying to store in the originalQty variable but there is an error.How do i store the result in an int variabe
public int prodQty( String prodid){
int originalQty = 0;
try {
String sql="select QUANTITY from PRODUCT where productid='"+prodid+"' '";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
originalQty=rs.getInt(7);
}
}
catch (SQLException ex) {
}
System.out.println(originalQty);
return originalQty;
}
Use
originalQty=rs.getInt("QUANTITY");
And you have a quote too much in your query
... where productid='"+prodid+"' '";
^--------here. Remove that
If the input is a number you can remove the quotes entirely.
And you should actually use Prepared Statements that handle escaping inputs automatically and prevent SQL injections.
Some advice.
Always use column name.
Use prepared statement.
Learn how to debug your program. That will tell you exactly why the error.
I am trying to create an event using the code below in java. However after I give it the input needed I check the database to find all of the fields containing null values. what should I do? Thank you in advance.
public void CreateEvent(User U){
try{
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
String d;
//getting inputfrom the user
System.out.print("Event Name \n");
d = inFromUser.readLine();
EventName = d;
System.out.println("Kindly Provide the start date(Format dd/MM/yyyy HH:mm)");
//parsing date from user using SimpleDateFormat
date = sdf.parse(inFromUser.readLine());
startDate = date.toString();
System.out.println("Kindly Provide the end date(Format dd/MM/yyyy HH:mm)");
date = sdf.parse(inFromUser.readLine());
d = date.toString();
endDate = d;
System.out.println("Where is the event:");
d = inFromUser.readLine();
Location= d ;
System.out.println("Description");
d = inFromUser.readLine();
Description= d;
//Get creator UserName
Creator = U.FullName;
MyJDBC.Insert(TableName, Fields, Values);
}
catch (IOException ex) {//catch the exception
ex.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
}
values is this
String Values= "'"+EventName+"','"+Location +"','"+Description+"','"+startDate+"','"+endDate+"','"+Creator+"'";
this is JDBC insert method
public void Insert(String TableName,String Fields, String Values){
try {
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "INSERT INTO " + TableName+ " (" +Fields+ ") VALUES ("+ Values+ ")" ;
stmt.execute(sql);
System.out.println("Successfully inserted record into database");
stmt.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
The code sample is not complete. Yet, what can be seen, is that you collect some variables like EventName and Location and later on you send values to the insert method, but that values is never filled.
Your updated question proves that: String in Java is immutable, you cannot change it after creation. Values will not be evaluated again, after the assignment has been done.
At the time you assign it, all variables used to fill it are null.
To solve your problem now, assign values right before you call the insert-method.
To improve your program, write a class DAO with a method saveEvent() that takes an EventVO as parameter.
The EventVO contains all the collected values as properties.
The save method will create the sql neccessary to insert or update the event.
Also: The java language has the convention, that variables name are lower case, you should stick to that.
i want to multiply 2 arrays and show to the table but this code doesn't work , here this code , please help me
public void hitung ()
int hasil = 0;
long nilai2 ;
int quan = 0 ;
int quans = 0;
try {
String sql = ("SELECT tbl_masakan.nama_masakan, banyak, tbl_masakan.harga_masakan FROM tbl_masakan, tbl_det_pesanan WHERE id_det_pesanan = '"+ id +"' and tbl_det_pesanan.id_masakan = tbl_masakan.id_masakan ");
ResultSet rsuser= cn.stt.executeQuery(sql);
rsmetadata = rsuser.getMetaData();
while (rsuser.next()) {
int size = 0;
if (rsuser != null)
{
rsuser.beforeFirst();
rsuser.last();
size = rsuser.getRow();
}
String str = rsuser.getString(2);
quan = Integer.parseInt(str);
String strs = rsuser.getString(3);
quans = Integer.parseInt(strs);
hasil = hasil + (quan*quans);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString());
}
txt1.setText(String.valueOf(hasil));
}
There some minor problems with your code.
There are variables defined but never used, as is the case with size and rsmetadata (which is not declared in the code you posted).
It is not necessary to retrive the columns from the database as Strings and then perform the conversion using Integer.parseInt(). You can retrieve them directly as Integers using rsuser.getInt(columnIndex).
The documentation for the method executeQuery(String sql) of the Statement class says that it returns "a ResultSet object that contains the data produced by the given query; never null" so checking for null is unnecessary.
My guess is that the cause of your problem (although you didn't actually said what was the output of your code) is the calculation of the size of the ResultSet. Observe that it leaves the cursor pointing to the last position (rsuser.last()), therefore your while(rsuser.next()){...} loop should run only once. If you actually need to calculate the size for some reason, you should do it before the while() loop and make sure to call rsuser.beforeFirst() again so that the cursor points to the beginning of the Resultset before entering the loop. In that case your code should look like this:
String sql = ...;
ResultSet rsuser= cn.stt.executeQuery(sql);
// calculate size
int size = 0;
if (rsuser.last()) {
size = rsuser.getRow();
rsuser.beforeFirst();
}
while (rsuser.next()) {
quan = rsuser.getInt(2);
quans = rsuser.getInt(3);
hasil = hasil + (quan*quans);
}
Lastly, observe that this method of calculating the size of the ResultSet is not without problems, all of which are clearly pointed out in this discussion:
How do I get the size of a java.sql.ResultSet?
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.