JDBC Choose Column - java

Here is my code:
import java.sql.*;
public class clazz{
public static void main(String[] args) {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database","root","password");
Statement stmt = (Statement) con.createStatement();
String insert = "INSERT INTO table VALUES ('value')";
stmt.executeUpdate(insert);
}catch(Exception e){
}
}
}
This works great and all, if there's only one column. How would I specify the column?

This works great and all, if there's only one column. How would I
specify the column?
Just specify the column name in the column list in your query.
String insert = "INSERT INTO table (colname1, colname2) VALUES ('value1','value2')";
Btw, I would recommend you to use PreparedStatement instead of Statement while executing SQL queries using JDBC in order to prevent SQL Injection.

Here is a demo.
create table t_customer (
id number(19, 0) not null,
first_name varchar2(50) not null,
last_name varchar2(50) not null,
last_login timestamp null,
comments clob null,
constraint pk_customer primary key(id)
)
public class InsertDemo {
private static final String CONNECTION_STRING =
"jdbc:oracle:thin:#oracle.devcake.co.uk:1521:INTL";
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
return;
}
Connection connection;
try {
connection = DriverManager.getConnection(CONNECTION_STRING,
"PROSPRING", "x******6");
} catch (SQLException e) {
return;
}
PreparedStatement preparedStatement;
try {
preparedStatement = connection.prepareStatement(
"insert into t_customer (id, first_name, last_name, last_login, " +
"comments) values (?, ?, ?, ?, ?)");
} catch (SQLException e) {
return;
}
try {
preparedStatement.setLong(1, 1L);
preparedStatement.setString(2, "Jan");
preparedStatement.setString(3, "Machacek");
preparedStatement.setNull(4, Types.TIMESTAMP);
preparedStatement.setNull(5, Types.CLOB);
preparedStatement.executeUpdate();
} catch (SQLException e) {
return; // 1
}
try {
connection.commit();
} catch (SQLException e) {
return;
}
try {
connection.close();
} catch (SQLException e) {
// noop
}
}
}

Related

Creating a new entry in SQL in a join table is giving me null values

#Override
public Order create(Order order) {
try (Connection connection = DBUtils.getInstance().getConnection();
PreparedStatement statement = connection
.prepareStatement(
"INSERT INTO orders(fk_customer_id) VALUES (?);" +
"SELECT order_id INTO #newid FROM orders WHERE fk_customer_id = ? " +
"ORDER BY order_id DESC LIMIT 1;" +
"INSERT INTO orders_items(fk_order_id, fk_item_id, quantity) VALUES (#newid, ?, ?);");) {
statement.setLong(1, order.getId());
statement.setLong(2, order.getId());
statement.setLong(3, order.getItem_id());
statement.setInt(4, order.getQuantity());
statement.executeUpdate();
LOGGER.info(readLatest());
return readLatest();
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return order;
}
Getting error in SQL syntax: near 'SELECT order_id INTO #newid FROM orders WHERE fk_customer_id = 1 ORDER BY order_' at line 1 -- when I try this syntax directly in SQL it works perfectly, so I don't understand?
For context, this is my readLatest() method:
public Order readLatest() {
try (Connection connection = DBUtils.getInstance().getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM orders ORDER BY order_id DESC LIMIT 1");) {
resultSet.next();
return modelFromResultSet(resultSet);
} catch (Exception e) {
LOGGER.debug(e);
LOGGER.error(e.getMessage());
}
return null;
}
and modelFromResultSet():
public Order modelFromResultSet(ResultSet resultSet) throws
SQLException {
Long order_id = resultSet.getLong("order_id");
Long id = resultSet.getLong("fk_customer_id");
return new Order(order_id, id);
}

Why doesn't my Java code create a table in an in-memory SQLite database and print the table name?

I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

Inserting values from java GUI into postgresql data base

I am having problems inserting data into a postgres table created using java. The created table part of the code works fine, its only when I am inserting values into the table that nothing happens. The code I am using to populate the table tt is:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String txt1 = jTextField1.getText();
int number = Integer.parseInt(txt1);
String name= jTextField2.getText();
String txt3 = jTextField3.getText();
int mean = Integer.parseInt(txt3);
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/tst", "postgres", "21262050");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String sql = "INSERT INTO tt(noun, max, nbr) VALUES(?, ?, ?)";
PreparedStatement pst = c.prepareStatement(sql);
pst.setString(1, name);
pst.setInt(2,mean );
pst.setInt(3, number);
pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(insrt.class.getName()).log(Level.SEVERE, null, ex);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new insrt().setVisible(true);
}
});
}
You're establishing autocommit to false.
After the auto-commit mode is disabled, no SQL statements are
committed until you call the method commit explicitly.
https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html#disable_auto_commit
Try executing c.commit() after pst.executeUpdate();

ORA-02289: sequence does not exist, cannot find my error

public static void main(String[] argv) {
try {
createTable();
insertRecordIntoTable("leo","123");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void createTable() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sequence = "CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20";
String createTableSQL = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(createTableSQL);
System.out.println(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
System.out.println("Table \"dbuser\" is created!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER,DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
private static void insertRecordIntoTable(String username, String password) throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String insertTableSQL = "INSERT INTO DBUSER1"
+ "(USER_ID, USERNAME, PASSWORD) VALUES"
+ "(ID_SEQ.NEXTVAL,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(insertTableSQL);
// execute insert SQL stetement
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();
System.out.println("Record is inserted into DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I cannot find the error when I try to create a sequence for my table.
When I try to insert some data in my table with the sequence it says it doesn't exist, but I did create it. Also I am not sure if i need a preparedStatement.setInt(1, seq_id.nextval); it gives an error but im not quite sure how I would do this
The solution might be adding the schema name (owner) before the name of sequence:
CREATE SEQUENCE some_nameOf_schema.ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999 MINVALUE 1 CACHE 20
You're preparing a statement with one SQL text, and executing the statement with two different SQL texts;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate(createTableSQL);
preparedStatement.executeUpdate(sequence);
...which is actually invalid according to the docs;
int executeUpdate(String sql)
throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
What you need to do is to prepare and execute two different statements;
preparedStatement = dbConnection.prepareStatement(createTableSQL);
preparedStatement.executeUpdate();
preparedStatement = dbConnection.prepareStatement(sequence);
preparedStatement.executeUpdate();
In general, it doesn't make much sense to CREATE database objects every time your application starts up, because this is something that's usually done only once, when you install/upgrade the database/schema the application uses.
However, if you really have to do it this way, the current solution could be improved so that the following points are considered:
Only execute the CREATE statements when the objects do not yet exist in the DB. This can be done by first inspecting the USER_OBJECTS data dictionary view.
Use a plain Statement instead of PreparedStatement for executing the DDL (prepared statements are only useful for DML operations that use input variables)
Handle JDBC resources (Connection / Statement / ResultSet) concisely and safely through the try-with-resources construct
Here's how the code could look like:
// query constants
private static final String CHECK_DB_OBJECT =
"SELECT 1 FROM user_objects WHERE object_name = ?";
private static final String CREATE_SEQUENCE =
"CREATE SEQUENCE ID_SEQ INCREMENT BY 1 MAXVALUE 99999999999999999999" +
" MINVALUE 1 CACHE 20";
private static final String CREATE_TABLE = "CREATE TABLE DBUSER1("
+ "USER_ID NUMBER(5) NOT NULL, "
+ "USERNAME VARCHAR(20) NOT NULL, "
+ "PASSWORD VARCHAR(20) NOT NULL, "
+ "PRIMARY KEY (USER_ID) "
+ ")";
/* clip the main method etc. */
/**
* Creates the table and sequence only if they do not already exist.
*/
private static void createTableAndSequenceIfAbsent() {
try (Connection dbConnection = DriverManager.getConnection(
DB_CONNECTION, DB_USER, DB_PASSWORD);
PreparedStatement ps = dbConnection
.prepareStatement(CHECK_DB_OBJECT)) {
if (!dbObjectExists(ps, "ID_SEQ")) {
executeDDL(dbConnection, CREATE_SEQUENCE);
}
if (!dbObjectExists(ps, "DBUSER1")) {
executeDDL(dbConnection, CREATE_TABLE);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean dbObjectExists(PreparedStatement ps,
String objectName) throws SQLException {
ps.setString(1, objectName);
ResultSet rs = ps.executeQuery();
// if the #CHECK_DB_OBJECT query returned a row, the object exists
return rs.next();
}
private static void executeDDL(Connection c, String sql)
throws SQLException {
try (Statement st = c.createStatement()) {
st.execute(sql);
}
}

Attempting to enter values to database tables using jdbc transaction

I'm attempting to enter a set of values to tables reservation,resdetails using database transactions. There are no exceptions thrown, but values are not being entered in to DB.Here i've used utilised java.sql.PreparedStatement.
public boolean addReservation(Reservation res, ArrayList<ReservationDetails> resdetlist) throws Exception {
connection = DBConnection.getDBConnection();
try {
System.out.println("A");
connection.setAutoCommit(false);
PreparedStatement ps1 = connection.prepareStatement("insert into reservation values(?,?,?,?)");
ps1.setString(1, res.getResid());
ps1.setBoolean(2, res.isCheckin_status());
ps1.setString(3, res.getRes_from());
ps1.setString(4, res.getRes_till());
int addedres = ps1.executeUpdate();
System.out.println("addres:" + addedres);
System.out.println("B");
if (addedres > 0) {
for (ReservationDetails resdet : resdetlist) {
//int addedresdet = addReservationDetails(resdet);
PreparedStatement ps2 = connection.prepareStatement("insert into resdetails values(?,?,?,?,?,?)");
ps2.setString(1, resdet.getResid());
ps2.setString(2, resdet.getNic());
ps2.setString(3, resdet.getPayment_id());
ps2.setString(4, resdet.getRoom_no());
ps2.setString(5, resdet.getType_of_accomodation());
ps2.setString(6, resdet.getDate_of_reservation());
int addedresdet = ps2.executeUpdate();
System.out.println("addedresdet:" + addedresdet);
System.out.println("C");
if (addedresdet <= 0) {
System.out.println("D");
connection.rollback();
return false;
}
}
} else {
System.out.println("E");
connection.rollback();
return false;
}
connection.commit();
} catch (Exception ex) {
// ex.printStackTrace();
connection.rollback();
} finally {
connection.setAutoCommit(true);
System.out.println("F");
}
return true;
}
If executeUpdate() returns <= 0 then nothing changed in the database, therefore there's no need to rollback the transaction. Also, if a problem occurred while inserting the entry (eg. a constraint violation, etc) then the executeUpdate() throws a SQLException. I would change you code to:
try {
connection.setAutoCommit(false);
PreparedStatement ps1 = ...
...
ps1.executeUpdate();
for (ReservationDetails resdet : resdetlist) {
PreparedStatement ps2 = ...
...
ps2.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
connection.rollback();
}
Also, don't forget to call close() on the PreparedStatements after you use them, and on the connection object at the end of the method.

Categories