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);
Related
This question already has answers here:
Getting the date from a ResultSet for use with java.time classes
(3 answers)
Closed 4 years ago.
I run a simple query to retrieve a row from a MySQL database.
I get ResultSet and I need to retrieve a LocalDateTime object from it.
My DB table.
CREATE TABLE `some_entity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(45) NOT NULL,
`text` varchar(255) DEFAULT NULL,
`created_date_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I need to retrieve some entity by id.
String SELECT = "SELECT ID, TITLE, TEXT, CREATED_DATE_TIME FROM some_entity WHERE some_entity.id = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(SELECT);
try {
selectPreparedStatement.setLong(1, id);
ResultSet resultSet = selectPreparedStatement.executeQuery();
if (resultSet.next()) {
Long foundId = resultSet.getLong(1);
String title = resultSet.getString(2);
String text = resultSet.getString(3);
LocalDateTime createdDateTime = null;// How do I retrieve it???
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve some entity by id.", e);
}
Try retrieving this as java.sql.Timestamp and then converting to LocalDateTime using Timestamp.toLocalDateTime:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
EDIT: As Gord Thompson pointed out in his comment, there's an even better solution when working with a recent enough JDBC driver:
resultSet.getObject(4, LocalDateTime.class)
This skips creating a redundant java.sql.Timestamp instance.
This question already has an answer here:
MySQL syntax error when executing SQL query
(1 answer)
Closed 6 years ago.
I am trying a simple insert into my table but my program says I have a SQL Syntax error. Any ideas?
SQL CODE
CREATE TABLE ticket (
start_time DATETIME NOT NULL,
end_time DATETIME NOT NULL,
seat VARCHAR(50) NOT NULL,
sep VARCHAR(50) NOT NULL,
price INT(50) NOT NULL,
foroom VARCHAR(50) NOT NULL,
printer INT(15) NOT NULL,
PRIMARY KEY (seat)
);
JAVA CODE
try
{
System.out.println("Attempting to connect...\n");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/baseis?autoReconnect=true&useSSL=false","root","");
System.out.println("Connection Succesful!!!");
String sql = "INSERT INTO ticket (start_time)" + " VALUES (?)";
PreparedStatement prepared = connection.prepareStatement(sql);
prepared.setString(1,"2016-07-17 19:00:00");
prepared.executeUpdate(sql);
}
catch(SQLException error)
{
System.out.println("Error: " + error.getMessage());
}
ERROR
Error: 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
You need to provide values for all NOT NULL columns, and don't provide the sql string to executeUpdate():
// set some values for the record
String seat = "";
String sep = "";
int price = 0;
String foroom = "";
int printer = 0;
String sql = "INSERT INTO ticket (start_time, end_time, seat, sep, price, foroom, printer) VALUES (?, ?, ?, ?, ?, ?, ?)";
PreparedStatement prepared = connection.prepareStatement(sql);
prepared.setString(1, "2016-07-17 19:00:00");
prepared.setString(2, "2016-07-17 20:00:00");
prepared.setString(3, seat);
prepared.setString(4, sep);
prepared.setInt(5, price);
prepared.setString(6, foroom);
prepared.setInt(7, printer);
prepared.executeUpdate();
You need to supply values for all columns declared as 'NOT NULL'
The best way to debug problems like this is to capture the actual SQL statement sent to the 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.
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);
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.