Error when trying to create prepared statement to update MySQL - java

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).

Related

Subtract scanner value from sql table value

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";

Java and SQL Database

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/

Oracle invalid identifier doesnt understand string

I'm having an issue with my query not working. This is the command variable.
When it executes it should be retrieving the tuples that have BSc as their degree. I have tested this in oracle directly and the query returns these. It is identical to the command statement.
When I print out command, the line looks exactly the same as my command that worked in oracle.
SELECT distinct fname, lname, student_id FROM student where degree='BA';
Yet, it should be printing out to the screen. The tables are loaded into oracle already.
I've been racking my brain with this issue but can't seem to find a fix!
The error I keep getting is:
ORA-00911: invalid character
What I do is I store in degree the result from scanner which is a string. So concatenating it in the command variable shouldn't make an issue -- the query looks identical to what works in oracle.
Could it be because it wants a char instead of a string? If it does, then how would I get it to make "BSc" as a char? Concatenating chars sounds dumb.
Relevant code below:
private String getDegree() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter degree code (either BA or BSc)");
return scan.next();
}
//get the degree name
String degree = getDegree();
//get statement and execute appropriate select
Statement stmt = con.createStatement();
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
System.out.println(command);
ResultSet result = stmt.executeQuery(command);
//determine number of columns
ResultSetMetaData metadata = result.getMetaData();
int columns = metadata.getColumnCount();
//print heading
System.out.println("\nFNAME LNAME STUD_ID");
System.out.println("====================================");
//loop through result and print columns
while (result.next()){
for (int i=1; i <=columns; i++){
System.out.print(result.getString(i)+spaces(15-result.getString(i).length()));
}
System.out.println();
}
`
In JDBC your SQL statement should not be terminated by semicolon.
Change
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "';";
to
String command = "SELECT distinct fname, lname, student_id FROM student"+
" where degree='"+ degree + "'";

Search Filter in Java and MySQL database

I am writing a code in Java where user can type a last name in a JTextField named lastname and then search for possible match in MySQL database. Say for example, user begins to type letter "M" (case insensitive and without double quotes), all the last name that starts with letter "M*" will display on JTable. If user types a second letter, say for example "A", the results on JTable will only display last names with "MA", then if user types third letter, say for example "N", JTable will only display all the last names with "MAN***" and so on..
I have read about
SELECT * FROM table WHERE lastname LIKE value
and tried to use it on my program, however, I am getting an error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxError.Exception: 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 '%' at line 1
Here's my partial code in event when there's key pressed in JTextField lastname:
private void lastNameKeyPressed(java.awt.event.KeyEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students_dbs";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "user1";
String databasePassword = "test";
PreparedStatement pst = null;
try{
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
System.out.println("Connected to the database.");
}catch(Exception e){
System.out.println("Failed to connect ot the database.");
}
try{
String sql = "SELECT studentno, lastname, firstname, middlename FROM student WHERE lastname LIKE '%" + lastname.getText() + "'%";
pst = conn.prepareStatement(sql);
result = pst.executeQuery();
studentsTable.setModel(DbUtils.resultSetToTableModel(result));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
I googled it for a day or two now, however, I am stuck. I'm kinda new in using LIKE in MySQL. Any kind help is very much appreciated! Thank you in advance!
The position of the last ' char is wrong:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " '% ";
should be:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " %' ";
Try this:
String SQL="Select name from tablename where like %";
pst = conn.prepareStatement(sql);
pst.setString(1, txnam.gettext()+"%");
put one textfield for u to type
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname=?";
pst = conn.prepareStatement(sql);
pst.setString(1,jTextField1.getText());
result = pst.executeQuery();
you can use this code :
this is sql code
and then rename youre Jtabble, Like model in picture one. then call method in here initcomponent(){selectDataTable(""); }. then make event key released in youre textfield, and then write this in the event selectDatatable(textfield.gettext()); Done

What facility does java provide for getting input from the command line for the executeUpdate() method in SQL

Scanner input = new Scanner(System.in);
System.out.println("Enter Staff Name: ");
String staffName = input.nextLine();
System.out.println("Enter Department Name: ");
String department =Input.nextLine();
stmt.executeUpdate("insert into staff (StaffName,department) " + "values " +
staffName,department);
This gives me an error and asks me to check the SQL manual.Is it even possible?
It is possible, since it happened. Strings must be enclosed in quotes in SQL:
insert into foo (bar, baz) values ('hello', 'world');
Learn to use prepared statements instead of string concatenations, to make your queries work, and not be subject to SQL injection attacks:
PreparedStatement stmt = connection.prepareStatement("insert into staff (StaffName, department) values (?, ?)");
stmt.setString(1, staffName);
stmt.setString(2, department);
stmt.executeUpdate();
Using the above, you don't need to mess with quotes nor escape them inside the strings.
It's not necessarily the user input being formatted incorrectly. The INSERT into should be formatted like:
INSERT INTO <table_name>
VALUES (<1>, <2>, ... <n>);
To format your SQL query correctly, you could try:
String sql = "INSTERT INTO STAFF (StaffName, department) VALUES (\'" +
staffName + "\', \'" + department + "\');";

Categories