Unknown column 'v_plateno' in 'where clause' in Java - java

this is my Table vehicletlb !
Field Type
v_branch varchar(255) NULL
v_segment varchar(255) NULL
v_company varchar(255) NULL
v_name varchar(255) NULL
v_plateno varchar(255) NULL
v_seats int(11) NULL
v_fuel varchar(255) NULL
v_priceperkm int(11) NULL
v_driver varchar(255) NULL
Now I am trying to Update the table using Prepared Statement in Servlet. But unfortunately it is giving error for unknown column:v_plateno
Also the update query is working fine for other Tables in the database
public void updateVehicle(Vehicle vehicle) {
String updateQuery = "UPDATE vehicletlb SET v_branch=?, v_segment=?, v_company=?, v_name=?, v_seats=?, v_fuel=?, v_priceperkm=?, v_driver=? WHERE v_plateno = ? ";
try {
pStmt = dbConnection.prepareStatement(updateQuery);
pStmt.setString(1, vehicle.getVbranch());
pStmt.setString(2, vehicle.getVsegment());
pStmt.setString(3, vehicle.getVcomp());
pStmt.setString(4, vehicle.getVname());
pStmt.setInt(5, vehicle.getVseats());
pStmt.setString(6, vehicle.getVfuel());
pStmt.setInt(7, vehicle.getVprice());
pStmt.setString(8, vehicle.getVdriver());
pStmt.setString(9, vehicle.getVplateno());
pStmt.executeUpdate();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
I am using Apache Tomcat 7.0
But it gives error
Unknown column 'v_plateno' in 'where clause'
How can I solve it !!!!

There were no errors in the program and now
I tried Refreshing the Browser, and it started working
Thanks for support !

Related

Updating row in table causing the row to be duplicate

I am facing a strange problem when I try to update a certain row in my table.
I am using the Connection class from java.sql library. Following is my table script:
CREATE TABLE `crd_web_request` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(30) NOT NULL,
`trn_notes` varchar(200) DEFAULT NULL,
`trn_date` date NOT NULL,
`amount` double(20,3) DEFAULT '0.000',
`other_amount` double(20,3) DEFAULT '0.000',
`card_fees` double(20,3) DEFAULT '0.000',
`shipping_fees` double(20,3) DEFAULT '0.000',
`sys_trtype_id` int(11) DEFAULT NULL,
`crd_agent_mast_id` int(11) DEFAULT '0',
`sys_phase_id` int(11) DEFAULT '0',
`sys_user_id` int(11) DEFAULT NULL,
`cust_aname` varchar(250) DEFAULT NULL,
`cust_ename` varchar(250) DEFAULT NULL,
`sys_nationality_id` int(11) DEFAULT NULL,
`passport_id` varchar(45) DEFAULT NULL,
`sys_doc_type_id` int(11) DEFAULT NULL,
`cust_doc_id` varchar(45) DEFAULT NULL,
`cust_email` varchar(250) DEFAULT NULL,
`cust_address` varchar(250) DEFAULT NULL,
`cust_tel` varchar(30) DEFAULT NULL,
`card_holder_name` varchar(400) DEFAULT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`cardType_ID` int(20) DEFAULT NULL,
`sys_org` int(2) DEFAULT NULL,
PRIMARY KEY (`id`,`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=237 DEFAULT CHARSET=utf8;
and following is my java code to update the table:
Statement stmt = null;
String query = "UPDATE smcpp16.crd_web_request SET status = 1 WHERE order_id = '" + orderId + "'";
try {
stmt = conn.createStatement();
System.out.println(query);
stmt.execute(query);
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
I can it figure out why this is happening. Every time when executing the update statement, the table inserts a new record with the same values of the updated row. Can you please help?
I removed the closing of the connection from this code and the duplication is not happening any more.
I just removed:
conn.close();
It is a practice to close the connection in the finally block, something like this :
try{
// update data
}
catch{
//catch exception
}
finally{
//close connection
conn.close();
}
Let me know if this helps.

How to use JDBC wildcards in preparedstatement to create mysql table [duplicate]

This question already has answers here:
How to use dynamic table name in SELECT query using JDBC
(3 answers)
Closed 6 years ago.
String sql2 = "create table ? ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, username);
stmt2.execute();
stmt2.close();
from above statements, i got error message('john' as table name):
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 ''john' ( id int not null
auto_increment, fullname varchar(30) not null, primary ' at line 1
eclipse says the error is in this line:
stmt2.execute();
please help guys...tq
You can't use a parameter for the table name in a CREATE TABLE statement.
Instead simply build the SQL string using the variable:
String sql2 = "create table " + username + " ( id int not null auto_increment, fullname
varchar(30) not null, primary key (id) )";
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(sql2);

Java JDBC adding automatic value to database

I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.

MySQL database has duplicate entries despite unique constraint

So mySQL database keeps accepting duplicate entries despite the unique constraint I've added. I've been trying to look for a similar question but could not find anything related. I don't know if my prepared statement is wrong or if mySQL database is set up wrong. Here is my code:
Connection con = DB.getConnection();
PreparedStatement ps = null, ps1 = null, ps2 = null, ps3 = null, ps4 = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("insert into users(user_id, username, password, email, phone_number,"
+ "name, fb_id, bio) values (DEFAULT, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, username);
ps.setString(2, hashedPassword);
ps.setString(3, email_address);
ps.setString(4, phone_number);
ps.setString(5, name);
ps.setString(6, fb_id);
ps.setString(7, bio);
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace(); }
my table has the following columns:
user_id int(11) PRIMARY,
username varchar(20) UNIQUE,
password varchar(100),
email varchar(30) UNIQUE,
phone_number varchar(10) UNIQUE,
fb_id varchar(20) UNIQUE,
bio FULL TEXT
I've created the table using phpmyadmin and username and fb_id correctly gives me the MySQLIntegrityConstraintViolationException, but email and phone_number does not give me any errors when inserting duplicate entries. Is there any reason why this would happen? I am pretty lost as to why the unique constraint is not being enforced...
PS. First time posting!
EDIT: Here is the results of SHOW CREATE TABLE users:
CREATE TABLE users (
user_id int(11) NOT NULL AUTO_INCREMENT,
username varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
password varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
email varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
phone_number varchar(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
name varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
fb_id varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
bio text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (user_id),
UNIQUE KEY username (username,email,phone_number),
UNIQUE KEY fb_id (fb_id)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1
You currently have your UNIQUE KEY setup as a composite key.
UNIQUE KEY username (username,email,phone_number)
This means that the combination of username, email and phone number must be unique. It is not specifying each individual column can't contain duplicate values.
For that you should add a UNIQUE INDEX to those columns individually where required. For example to make the email field a UNIQUE INDEX:
ALTER TABLE users ADD UNIQUE INDEX(email);

How to retrieve row in DB Table just added now in Java

Table
id int(11) No auto_increment Change Drop Primary Index Unique Fulltext
email varchar(45) latin1_swedish_ci No Change Drop Primary Index Unique Fulltext
billpayment tinyint(1) No Change Drop Primary Index Unique Fulltext
dispatch tinyint(1) No Change Drop Primary Index Unique Fulltext
address varchar(75) latin1_swedish_ci Yes NULL Change Drop Primary Index Unique Fulltext
phone int(11) Yes NULL Change Drop Primary Index Unique Fulltext
created_at datetime No Change Drop Primary Index Unique Fulltext
totalbillamount float Yes NULL Change Drop Primary Index Unique Fulltext
Java Code:
sql = "insert into session_shopping (email,billpayment,dispatch,address,phone,created_at,totalbillamount) values(?,?,?,?,?,?,?)";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, email);
ps.setBoolean(2, false);
ps.setBoolean(3, false);
ps.setString(4, "");
ps.setInt(5, 0);
java.util.Date date = new java.util.Date();
long t = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(t);
ps.setDate(6, sqlDate);
ps.setFloat(7, 00.0f);
int newId = ps.executeUpdate();
System.out.println("newId" + newId);
if (newId == 1) {
sql = "select * from session_shopping where id = ?";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, newId);
ResultSet reS = ps.executeQuery();
Session s = new Session();
s.setId(reS.getInt("id"));
s.setEmail(reS.getString("email"));
System.out.println("retreived");
return s;
} else {
System.out.println("unable to save");
}
This code fails because int newId is boolean
What i want to do is. I want to retrieve the row which i added just now.
executeUpdate will return the number of rows affected, not the current row .
Try this
ResultSet rs = aStatement.executeQuery("SELECT LAST_INSERT_ID()");
while(rs.next())
{
key = rs.getInt(1);
}
The value returned by executeUpdate has nothing to do with your ID.
Before we go to getting your ID, you can start off by setting email in the Session from your email variable rather than pulling it back out of the database.
As things stand, the only way I can think of to get the newly inserted ID is by changing your SQL thus:
sql = "select max(id) from session_shopping";
This will give you problems if you get another insert before you pick out the maximum ID though. To prevent that, put the select in the same transaction as your insert.

Categories

Resources