Error while trying to save input to SQL using JAVA - java

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();

Related

Error in SQL syntax when trying to write to the database with Java

I'm working with mvc in java to connect to a database. The setData methord seams to not be working and not sure why. My database is called checker and the table info. connection works fine and can read data from db to textfields but when I place data into textfields I get an error.
public static void setData()
{
try
{
String query2 = "INSERT INTO info(name,dob,age,email,address) VALUES"+
"("+name+","+dob+","+age+","+email+","+address+")";
statement.executeUpdate(query2);
}catch(Exception ex)
{
System.out.println(ex);
}
}
the view class has the addBtn button that tries to set the data to the db.
public void actionPerformed(ActionEvent e)
{
conn.name = nameBox.getText();
conn.dob = nameBox.getText();
conn.age = ageBox.getText();
conn.dob = dobBox.getText();
conn.email = email.getText();
conn.setData();
System.out.println(nameBox.getText()+" "+ dobBox.getText()+" "+
ageBox.getText()+" "+ email.getText()+" "+addrBox.getText());
}
this error pops up:
java.sql.SQLSyntaxErrorException: 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 'taylor,01-03-04,14,jt#gmail.com,123 harris blvd)' at line 1
You should have your name quoted "('"+name+"' (there is single quotation mark there '). The same will apply for any other string type values - email and address.
Besides, I would rather use prepared statements for that, so quotations etc will be done for you.
MariaDB insert example:
INSERT INTO person (first_name, last_name) VALUES ('John', 'Doe');
In your case (JDBC) Change to use bind variables:
try {
String query2 = "INSERT INTO info(name,dob,age,email,address) VALUES(?,?,?,?,?)";
statement.setString(1, name);
statement.setString(2, dob);
statement.setString(3, age);
statement.setString(4, email);
statement.setString(4, address);
statement.executeUpdate(query2);

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/

net.ucanaccess.jdbc.UcanaccessSQLException: attempt to assign to non-updatable column

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();

jdbc Error, unable to connect to sql

i want to use database in my project, then i use this code for test( from jdbc tutorialspoint )
and change it for my code and db
then i get this error:
Creating statement...
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 'FROM test SET name=eee WHERE id=1' at line 1
Error: unable to connect to SQL!
java.sql.SQLException: 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 'FROM test SET name=eee WHERE id=1' at line 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1600)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1695)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3020)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2949)
at com.mysql.jdbc.Statement.execute(Statement.java:538)
at Test.main(Test.java:49)
my code:
import java.sql.*;
import java.math.*;
public class Test {
final static String DB_URL = "jdbc:mysql://localhost/testdb";
final static String USER = "root";
final static String PASS = "";
final static String JDBC_DRIVER="com.mysql.jdbc.Driver";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
Boolean ret = stmt.execute(sql);
System.out.println("Return value is : " + ret.toString() );
int rows = stmt.executeUpdate(sql);
System.out.println("Rows impacted : " + rows );
sql = "SELECT id,name FROM test";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.print("ID: " + id);
System.out.print(", name: " + name);
}
rs.close();
stmt.close();
conn.close();
}
catch(ClassNotFoundException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
catch(IllegalAccessException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: access problem while loading!");
System.exit(2);
}
catch(InstantiationException ex) {
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
catch (SQLException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
System.out.println("\n" + ex.getMessage());
System.out.println("Error: unable to connect to SQL!");
System.exit(4);
}
}
}
my database is:
Picture of my DB
i see this page
but it doesn't help me!
At first your statement is not valid update statement. It has convention:
update <tableName> set <column> = '<newValue>';
This is the simpliest update statement. It will update all rows. Then you can add where clause to make selection of rows. Check this out.
Secondly, you are directly adding values for columns and aren't wrapping value(s) into single quotes (they has to be wrapped otherwise it won't work). To fix it you need to add single quotes like:
set name = 'value';
Sure, this works but i don't like this approach. It's very dangerous and unsafe. I suggest you to use parametrized statements which are much more safe (beware of SQL injection) and more human-readable.
Simple example of an usage of PreparedStatement:
String sql = "UPDATE test SET name = ? WHERE id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, <nameValue>); // binding value for name column
ps.setInt(2, <idValue>); // binding value for where clause
ps.executeUpdate(); // executes statement
I would like to mention a few main advantages of PreparedStatements:
They are precompiled, database-side caching of the SQL statement leads
to overall faster execution and the ability to reuse the same SQL
statement in batches.
Automatic prevention of SQL injection attacks by built-in escaping of
quotes and other special characters.
Eases setting of non-standard Java objects in a SQL (Date, Time,
Timestamp, BigDecimal, Blob, etc.)
This Query is not correct
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
modify it to
String sql = "UPDATE test SET name='eee' WHERE id=1";
Change String sql = "UPDATE name FROM test SET name=eee WHERE id=1"; to
String sql = "UPDATE test SET name='eee' WHERE id=1";
Another good option for constructing queries is to use "Prepared statements" - take a look at the oracle tutorial - link
It helps to avoid problem with quotes like in your case and provides greater sequrity. And as I remember it provides some preparation which help to execute queries faster.
replace:
String sql = "UPDATE name FROM test SET name=eee WHERE id=1";
on
String sql = "UPDATE name FROM test SET name='eee' WHERE id=1";

Java PreparedStatement RETURN_GENERATED_KEYS not working

I am trying to get the identity column returned to my java program when doing a SQL insert. I am getting the following error when running the code
Uncaught exception thrown in one of the service methods of the
servlet: Cocoon. Exception thrown : java.lang.AbstractMethodError: java/sql
/Connection.prepareStatement(Ljava/lang/String;I)Ljava/sql/PreparedStatement;
Here is the code I am running.
private void insertUserInputParameters(ReportData rptData){
UserInputParameters userParams = rptData.getUserInputData();
StringBuilder sql = new StringBuilder();
PreparedStatement pstmt = null;
ResultSet rs = null;
int userDataId = -1;
//Get a database connection.
sl = ServiceLocator.getInstance();
ds = sl.getDataSource("jdbc/collegeguide");
con = ds.getConnection();
con.setReadOnly(false);
sql.append("insert into cpgusrdtaf (statecd, addr1, addr2, city, state, ");
sql.append("zipcode, dependent, shdindic, marstatus, residency, prntatge, ");
sql.append("fincome, mincome, pincome, taxspaid, taxreturn, elig1040, ");
sql.append("gincome, pcash, inetwrth, bnetwrth, pbenefit, paddlinf, ");
sql.append("puntax, pdslcwrk, smstatus, sresidncy, studtr, stud1040, ");
sql.append("sadjinc, sincome, spincome, sdslcwrk, studtax, scash, ");
sql.append("sinvest, snetwrth, saddlinf, suntax, househld, nmbrsch, ");
sql.append("studact, studsat, schools, housing) ");
sql.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, ");
sql.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//This line of code is where I get the error**
pstmt = con.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
//If I remove the 'Statement.RETURN_GENERATED_KEYS' I do not get the error.**
pstmt = con.prepareStatement(sql.toString());
setStatementValues(pstmt, userParams);
pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if(rs.next()){
userDataId = rs.getInt(1);
}
I am not allowed to use stored procedures, so I cannot go that route. Any help would be greatly appreciated
I am using java 1.5
Thanks in advance
Doug
Assuming the arguments/parameters are balanced
(please confirm the query executes natively, and that the driver supports the RETURN_GENERATED_KEYS),
Can you try to use RETURN_GENERATED_KEYS as part of the argument to an executeUpdate call?
pstmt = con.createStatement();
pstmt.executeUpdate(sql.toString(), Statement.RETURN_GENERATED_KEYS);
EDIT:
Just read your note about using DB2. According to http://publib.boulder.ibm.com/infocenter/db2luw/v9r7/index.jsp?topic=%2Fcom.ibm.db2.luw.apdv.java.doc%2Fsrc%2Ftpc%2Fimjcc_t0057053.html
_Restriction: For IBM Data Server Driver for JDBC and SQLJ version 3.57 or later, the following form is not valid for inserting rows into a view on a DB2® for z/OS® data server.
Connection.prepareStatement(sql-statement,
Statement.RETURN_GENERATED_KEYS);_
this way it works for me:
prepStmt = con.prepareStatement(sql, new String[]{"NameOfIDField"});
I once had a problem with an oracle db where this was not working if the table has many fields.
But the above is working for me even with 60 fields.
My JT400.jar file was an older version. I downloaded the latest jar file from sourceforge and the problem was solved.
Try with Statement
Statement st = null;
ResultSet rs = null;
st = con.createStatement();
String query = " INSERT INTO refac_folios
([usuario], [estatus]) VALUES ('" + usuario + "'," + Vista_FoliosRefacciones.ESTATUS_CREADO )" ;
Integer afectadas = st .executeUpdate( query, Statement.RETURN_GENERATED_KEYS );
if (afectadas > 0){
rs = st.getGeneratedKeys();
if (rs .next()) {
folio = rs.getInt(1);
}
rs.close();
}
st.close();

Categories