I'm trying to subtract a scanner input from a table value. Here's a screenshot of my table:
Here's what my code looks like:
String url = "jdbc:mysql://localhost:3306/Project";
String username = "x";
String password = "y";
try {
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like to buy?");
int purchase_id = scanner.nextInt();
System.out.println("How many would you like to purchase?");
int quantity = scanner.nextInt();
Connection conn = DriverManager.getConnection(url, username, password);
Statement myStmt = conn.createStatement();
String sql = "update seattleBranch set inventory = " + quantity + "where item_id = 001";
myStmt = conn.prepareStatement(sql);
((PreparedStatement) myStmt).executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
The output of my code is:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'item_id = 001' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at branchComms.main(branchComms.java:27)
Here's what I want my table to look like after subtracting 100 (my scanner input quantity):
I'm unsure as to why subtracting my scanner variable (quantity) doesn't work, and I would appreciate any corrections to my code.
You are missing a space in the query before the where part, it should be like:
String sql = "update seattleBranch set inventory = " + quantity + " where item_id = 001";
Related
I am new to java and am trying to get used to the syntax and pushing data to a MySQL table. I am having this problem and can't figure what I have done wrong. When executing my update command it gives the following error.
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''occupation' = 'cat' WHERE first_name = 'kevin' AND last_name = 'hudgens'' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at Driver.updateContact(Driver.java:172)
at Main.main(Main.java:119)
main file
System.out.println("Please enter the first name of the contact you want to update.");
first_name = input.nextLine();
System.out.println("Please enter the last name of the contact you want to update.");
last_name = input.nextLine();
System.out.println("Are you sure you want to update " + first_name + " " + last_name
+ "'s information. YES or NO");
String verifyUpdate = input.nextLine();
// lower for comparison
// verifyUpdate = verifyUpdate.toLowerCase();
if (verifyUpdate.equals("YES")) {
break;
} else if (verifyUpdate.equals("NO")) {
System.out.println(
"Please enter the correct first and last name of the contact you would like to update");
} else {
System.out.println("You didnt enter the correct answer. YES or NO");
}
}
// inform user what they can update
System.out.println("What would you like to update? Options are:"
+ "\nFIRST NAME \n LAST NAME \n PHONE NUMBER \n EMAIL \n OCCUPATION");
// Collect the choices
String updateColumnChoice = input.nextLine();
System.out.println("What would you like to update it to? ");
String updatedValue = input.nextLine();
driver.updateContact(first_name, last_name, updateColumnChoice, updatedValue);
here is the prepared statement
public static void updateContact(String first_name, String last_name, String updatedColumn,
String toBeUpdatedValue) {
try {
// Get connection to database
Connection myConn = DriverManager.getConnection(info);
// Create sql command for deleting
String query = "UPDATE contacts SET ? = '?' WHERE first_name = '?' AND last_name = '?' ";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, updatedColumn);
preparedStmt.setString(2, toBeUpdatedValue);
preparedStmt.setString(3, first_name);
preparedStmt.setString(4, last_name);
// push prepared statement to the database
preparedStmt.executeUpdate();
// close the connection to the database
myConn.close();
} catch (Exception exc) {
exc.printStackTrace();
}
}
Any help on this would be greatly appreciated. Along with any general criticism on my code.
As far as I know, you can use PreparedStatement's parameters only for values, not for metadata. If you need updatedColumn to be dynamic, you can do this:
String query = "UPDATE contacts SET " + updatedColumn + " = '?' WHERE first_name = '?' AND last_name = '?' ";
Note that you will have to make sure that updatedColumn is properly quoted/escaped, especially if it's coming from user data (i.e. SQL injection attack).
I'm trying to input my details in MySQL using Java.
But I keep on having following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?, ?)' at line 1
Here is my code:
Vehicle vehicle = new Vehicle();
int vType;
System.out.println("Please enter Vehicle Type\n1 = Car\n2 = Van\n3 = Motorbike\n4 = Motorbike");
vType = input.nextInt();
if (vType==1){
System.out.println("Car Brand: ");
vehicle.setvBrand(input.next());
System.out.println("Car License Plate: ");
vehicle.setvLicense(input.next());
try {
Connection dbConn = DriverManager.getConnection(url,user,pass);
String parkCar = "INSERT INTO car_park_details(vehicle_brand, vehicle_license) values( ?, ?)";
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.executeUpdate(parkCar);
park.setString(2,vehicle.getvBrand());
park.setString(3, vehicle.getvLicense());
park.execute();
System.out.println("Try daw check sa DB MYONG!");
}
catch (Exception ex){
System.out.println("Error" + ex);
}
}
Am I doing it wrong? I'm a begginer Java Developer. thanks for the help.
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.setString(1, vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();
PreparedStatement set parameters index starts from 1.
Try as below, i.e run executeUpdate() without parameters and only after you have set your parameters to the PreparedStatement:
PreparedStatement park = dbConn.prepareStatement(parkCar);
park.setString(1,vehicle.getvBrand());
park.setString(2, vehicle.getvLicense());
park.executeUpdate();
So I am trying to create a application that simulates a online video store. I have created a database on Workbench and I am trying to create a if statement that checks if the user input matches those on the emails and passwords on the database. But I either get a error about the connection or about the driver. Hoping someone can help me out, thanks!
Here is the Java code
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Scanner input = new Scanner(System.in);
String answer = "";
String sql = "";
String email = "";
String password = "";
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull [root on Default schema]", "<username>", "<password>");
Statement myStmt = myConn.prepareStatement(sql);
ResultSet rs;
while(!answer.equals("n") || !answer.equals("y") )
{
System.out.print("Do you have an account? (Y/N) : ");
answer = input.nextLine();
if(answer.toLowerCase().equals("n"))
{
System.out.println("Please enter the email and password for your new account.");
System.out.print("Email: ");
email = input.nextLine();
System.out.print("Password: ");
password = input.nextLine();
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
myStmt.executeUpdate(sql);
}
else if(answer.toLowerCase().equals("y"))
{
System.out.print("\nEmail: ");
email = input.nextLine();
System.out.print("\nPassword:");
password = input.nextLine();
rs = myStmt.executeQuery(sql);
if(!rs.absolute(1))
{
System.out.println("You do not have an account. Please create one.");
continue;
}
}
else{
System.out.println("Invalid input. Please try again.");
continue;
}
}
Here is my SQL script
create database users;
use users;
create Table Accounts(
UserEamil Char(20) NOT NULL ,
UserPassword Char(20) NOT NULL
);
Here is my error:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
This code is not going to work as the values have not been set
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
myStmt.executeUpdate(sql);
what you should do is create a PreparedStatement using the sql and then call setString for each paramater like
sql = "insert into accounts "
+ " (UserEmail, UserPassword)" + " values (?, ?)";
Statement myStmt = myConn.prepareStatement(sql);
myStmt.setString (1, email);
myStmt.setString (2, password);
myStmt.executeUpdate ();
note
Currently at the top of your code you have
Connection myConn = DriverManager.getConnection("....");
Statement myStmt = myConn.prepareStatement(sql);
but the value of sql at this time is an empty string - it will not work
note2
Consult this answer for how to set your connection String correctly
Have you downloaded the mysql jdbc driver?
You should be able to fix it by adding the classpath:
C:\test>java -cp c:\test\mysql-connector-java-5.1.8-bin.jar;c:\test JDBCExample
Taken from:
https://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/
try{
//taking input from user about how much balance
Scanner input = new Scanner(System.in);
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://c://Bibek//Atmcard.accdb";
System.out.print("\nConnecting to database...");
con = DriverManager.getConnection(url);
st = con.createStatement();
System.out.println("\n Enter balance you want to withdraw:\n");
balance = Double.parseDouble(input.nextLine());
String sql = "select AccountBalance From Atm";
result = st.executeQuery(sql);
while(result.next()){
//assigning balanceFromDb to deduct and update in database
Double balanceFromDb = result.getDouble("AccountBalance");
balanceFromDb=balanceFromDb-balance;
result.updateDouble("AccountBalance", balanceFromDb);
result.updateRow();
}
}catch(Exception ex){
System.err.println(ex.toString());
}
output: Connecting to database...
Enter balance you want to withdraw:
20
net.ucanaccess.jdbc.UcanaccessSQLException: attempt to assign to non-updatable column
Check the Atm object in the access database and make sure it is a table and not a query. Also check the datatype for AccountBalance and make sure that it is an editable field. If it is auto incremented or calculated you will not be able to update it.
Edit: looks like you have to declare it an update able cursor. Here is the example from ucanacces on source forge http://ucanaccess.sourceforge.net/site.html
Using updatable ResultSet
PreparedStatement ps = super.ucanaccess.prepareStatement( "SELECT * FROM T1", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE, ResultSet.CLOSE_CURSORS_AT_COMMIT);
rs = ps.executeQuery();
rs.next();
rs.updateString(2, "show must go off");
rs.updateRow();
I want to update the esal of emp table in my database dynamically but the query is generating error
import java.sql.*;
import java.util.*;
class JdbcEx6
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection ob = DriverManager.getConnection("jdbc:odbc:mysql1","root","root123");
Statement st = ob.createStatement();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the empid");
int eno = sc.nextInt();
System.out.println("Enter the increment");
int inc = sc.nextInt();
String myquery = "update emp set esal=esal+"+inc+"where eno="+eno;/*error here*/
int count = st.executeUpdate(myquery);
ob.close();
if(count==0)
System.out.println("Invalid employee Id provided");
else
System.out.println("Updated successfully");
}
}
/*manual that corresponds to your MySQL server version for the right syntax to use near 'eno=100' at line 1
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
at JdbcEx6.main(a7.java:18)*/
As others explain, the problem can be solved by adding a whitespace to the where:
String myquery = "update emp set esal=esal+" + inc + " where eno="+eno;
//....................................................^ here
int count = st.executeUpdate(myquery);
A better solution would be to use PreparedStatement rather than plain string concatenation. Here's an example:
//query is more readable and easier to understand
//this way is easier to spot problems in the query
//? means a parameter to use in the query
String myquery = "update emp set esal=(esal+?) where eno=?";
//the connection prepares the query
PreparedStatement pstmt = ob.prepareStatement(myquery);
//set the parameters in the PreparedStatement
pstmt.setInt(1, inc);
pstmt.setInt(2, eno);
//execute the statement, which will replace the ? by the parameters
int count = pstmt.executeUpdate();
String myquery = "update emp set esal=(esal+'"+inc+"') where eno='"+eno"';
This works
You are not including spaces correctly in your query. SQL queries in java need spaces correctly just like they do in standard SQL usage.