Can any one help me java.sql.SQLException: ORA-00936: missing expression - java

package controller;
import pojo.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConn {
int found=0;
public boolean register(Member c)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
System.out.println("Data base is connected");
rs= stmt.executeQuery("select USERID from member");
System.out.println("Hi");
while(rs.next())
{
System.out.println("bye");
if((c.getUserId()).equals(rs.getString(1)) )
{
System.out.println("bye");
found=1;
break;
}
}
if(found==1)
{
return false;
}
else
stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"',,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')");
return true;
}
catch(ClassNotFoundException e)
{
System.out.print(e);
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
public boolean login(String userid, String password)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
rs= stmt.executeQuery("select userid, password from member where userid = '"+userid+"'");
if(rs==null)
{
return false;
}
else
{
while(rs.next())
{
String uid,pass;
uid=rs.getString(1);
pass=rs.getString(2);
if(password.equals(pass))
{
return true;
}
else
{
return false;
}
}
}
}
catch(ClassNotFoundException e)
{
System.out.print(e);
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
}
I am invoking the code from one servlet. It is showing me the following output.Though the same code is working correctly in somewhere else:
Output:
Data base is connected
Hi
java.sql.SQLException: ORA-00936: missing expression
Can anyone help me with the problem.

In your insert you have the following
+c.getAddress1()+"',,'"+c.getAddress2()+
There should be only one comma instead of two

I suggest to use PreparedStatement to avoid such error.
Advantage of using PreparedStatement over Statement
A SQL statement is precompiled and stored in a PreparedStatement object.
This object can then be used to efficiently execute this statement multiple times.
Reduces execution time.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters
Read more PreparedStatements and performance
See Java Tutorial on Using Prepared Statements
sample code:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
Find complete Sample example here to learn more about it.

Use prepared statements to avoid such issues. This will also avoid issues which you may face because of certain special characters like single quotes etc.
If not, then try one of the following:
If there is no column between address1 and address2, then use below (extra comma removed):
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"','"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);
If there is supposed to be an empty value that has to be inserted, then use below (an empty field is inserted using ,'', )
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"', '' ,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);

In your insert statement you can specify which columns you insert/update that would correspond to the SQL syntax having insert into member (col1, col2) values (val1, val2). The number of columns should be exactly the same before and after values in parenthesis. Incorrect number of columns or values are caused the error.

Related

How do I list multiple databases with their tables by using "Show Tables" via Java?

I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA

How do I get the last inserted primary key? [duplicate]

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can I achieve this using JDBC API?
If it is an auto generated key, then you can use Statement#getGeneratedKeys() for this. You need to call it on the same Statement as the one being used for the INSERT. You first need to create the statement using Statement.RETURN_GENERATED_KEYS to notify the JDBC driver to return the keys.
Here's a basic example:
public void create(User user) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
Note that you're dependent on the JDBC driver as to whether it works. Currently, most of the last versions will work, but if I am correct, Oracle JDBC driver is still somewhat troublesome with this. MySQL and DB2 already supported it for ages. PostgreSQL started to support it not long ago. I can't comment about MSSQL as I've never used it.
For Oracle, you can invoke a CallableStatement with a RETURNING clause or a SELECT CURRVAL(sequencename) (or whatever DB-specific syntax to do so) directly after the INSERT in the same transaction to obtain the last generated key. See also this answer.
Create Generated Column
String generatedColumns[] = { "ID" };
Pass this geneated Column to your statement
PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
Use ResultSet object to fetch the GeneratedKeys on Statement
ResultSet rs = stmtInsert.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Inserted ID -" + id); // display inserted record
}
When encountering an 'Unsupported feature' error while using Statement.RETURN_GENERATED_KEYS, try this:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BATCHID is the auto generated id.
I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:
private int insertQueryReturnInt(String SQLQy) {
ResultSet generatedKeys = null;
int generatedKey = -1;
try {
Statement statement = conn.createStatement();
statement.execute(SQLQy);
} catch (Exception e) {
errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
try {
generatedKey = Integer.parseInt(readOneValue("SELECT ##IDENTITY"));
} catch (Exception e) {
errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
return generatedKey;
}
This blog post nicely isolates three main SQL Server "last ID" options:
http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.
Instead of a comment, I just want to answer post.
Interface java.sql.PreparedStatement
columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement.
Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.
SYNTAX «
Connection.prepareStatement(String sql, int autoGeneratedKeys)
Connection.prepareStatement(String sql, int[] columnIndexes)
Example:
PreparedStatement pstmt =
conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
columnNames « List out the columnNames like 'id', 'uniqueID', .... in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT statement.
SYNTAX «
Connection.prepareStatement(String sql, String[] columnNames)
Example:
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
Full Example:
public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
//"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
int primkey = 0 ;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
pstmt.setString(1, UserName );
pstmt.setString(2, Language );
pstmt.setString(3, Message );
if (pstmt.executeUpdate() > 0) {
// Retrieves any auto-generated keys created as a result of executing this Statement object
java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
if ( generatedKeys.next() ) {
primkey = generatedKeys.getInt(1);
}
}
System.out.println("Record updated with id = "+primkey);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
I'm using SQLServer 2008, but I have a development limitation: I cannot use a new driver for it, I have to use "com.microsoft.jdbc.sqlserver.SQLServerDriver" (I cannot use "com.microsoft.sqlserver.jdbc.SQLServerDriver").
That's why the solution conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) threw a java.lang.AbstractMethodError for me.
In this situation, a possible solution I found is the old one suggested by Microsoft:
How To Retrieve ##IDENTITY Value Using JDBC
import java.sql.*;
import java.io.*;
public class IdentitySample
{
public static void main(String args[])
{
try
{
String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs";
String userName = "yourUser";
String password = "yourPassword";
System.out.println( "Trying to connect to: " + URL);
//Register JDBC Driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//Connect to SQL Server
Connection con = null;
con = DriverManager.getConnection(URL,userName,password);
System.out.println("Successfully connected to server");
//Create statement and Execute using either a stored procecure or batch statement
CallableStatement callstmt = null;
callstmt = con.prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT ##IDENTITY");
callstmt.setString(1, "testInputBatch");
System.out.println("Batch statement successfully executed");
callstmt.execute();
int iUpdCount = callstmt.getUpdateCount();
boolean bMoreResults = true;
ResultSet rs = null;
int myIdentVal = -1; //to store the ##IDENTITY
//While there are still more results or update counts
//available, continue processing resultsets
while (bMoreResults || iUpdCount!=-1)
{
//NOTE: in order for output parameters to be available,
//all resultsets must be processed
rs = callstmt.getResultSet();
//if rs is not null, we know we can get the results from the SELECT ##IDENTITY
if (rs != null)
{
rs.next();
myIdentVal = rs.getInt(1);
}
//Do something with the results here (not shown)
//get the next resultset, if there is one
//this call also implicitly closes the previously obtained ResultSet
bMoreResults = callstmt.getMoreResults();
iUpdCount = callstmt.getUpdateCount();
}
System.out.println( "##IDENTITY is: " + myIdentVal);
//Close statement and connection
callstmt.close();
con.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
try
{
System.out.println("Press any key to quit...");
System.in.read();
}
catch (Exception e)
{
}
}
}
This solution worked for me!
I hope this helps!
You can use following java code to get new inserted id.
ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, quizid);
ps.setInt(2, userid);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
lastInsertId = rs.getInt(1);
}
It is possible to use it with normal Statement's as well (not just PreparedStatement)
Statement statement = conn.createStatement();
int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
}
else {
throw new SQLException("Creating failed, no ID obtained.");
}
}
Most others have suggested to use JDBC API for this, but personally, I find it quite painful to do with most drivers. When in fact, you can just use a native T-SQL feature, the OUTPUT clause:
try (
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(
"""
INSERT INTO t (a, b)
OUTPUT id
VALUES (1, 2)
"""
);
) {
while (rs.next())
System.out.println("ID = " + rs.getLong(1));
}
This is the simplest solution for SQL Server as well as a few other SQL dialects (e.g. Firebird, MariaDB, PostgreSQL, where you'd use RETURNING instead of OUTPUT).
I've blogged about this topic more in detail here.
With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id
like
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1
if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).
In my case ->
ConnectionClass objConnectionClass=new ConnectionClass();
con=objConnectionClass.getDataBaseConnection();
pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
pstmtGetAdd.setString(1, objRegisterVO.getAddress());
pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
int addId=pstmtGetAdd.executeUpdate();
if(addId>0)
{
ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
rsVal.next();
addId=rsVal.getInt(1);
}
If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.
See this answer...
How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
If you are using JDBC (tested with MySQL) and you just want the last inserted ID, there is an easy way to get it. The method I'm using is the following:
public static Integer insert(ConnectionImpl connection, String insertQuery){
Integer lastInsertId = -1;
try{
final PreparedStatement ps = connection.prepareStatement(insertQuery);
ps.executeUpdate(insertQuery);
final com.mysql.jdbc.PreparedStatement psFinal = (com.mysql.jdbc.PreparedStatement) ps;
lastInsertId = (int) psFinal.getLastInsertID();
connection.close();
} catch(SQLException ex){
System.err.println("Error: "+ex);
}
return lastInsertId;
}
Also, (and just in case) the method to get the ConnectionImpl is the following:
public static ConnectionImpl getConnectionImpl(){
ConnectionImpl conexion = null;
final String dbName = "database_name";
final String dbPort = "3306";
final String dbIPAddress = "127.0.0.1";
final String connectionPath = "jdbc:mysql://"+dbIPAddress+":"+dbPort+"/"+dbName+"?autoReconnect=true&useSSL=false";
final String dbUser = "database_user";
final String dbPassword = "database_password";
try{
conexion = (ConnectionImpl) DriverManager.getConnection(connectionPath, dbUser, dbPassword);
}catch(SQLException e){
System.err.println(e);
}
return conexion;
}
Remember to add the connector/J to the project referenced libraries.
In my case, the connector/J version is the 5.1.42. Maybe you will have to apply some changes to the connectionPath if you want to use a more modern version of the connector/J such as with the version 8.0.28.
In the file, remember to import the following resources:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mysql.jdbc.ConnectionImpl;
Hope this will be helpful.
Connection cn = DriverManager.getConnection("Host","user","pass");
Statement st = cn.createStatement("Ur Requet Sql");
int ret = st.execute();

How to perform one to one table INSERT query [duplicate]

I want to INSERT a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can I achieve this using JDBC API?
If it is an auto generated key, then you can use Statement#getGeneratedKeys() for this. You need to call it on the same Statement as the one being used for the INSERT. You first need to create the statement using Statement.RETURN_GENERATED_KEYS to notify the JDBC driver to return the keys.
Here's a basic example:
public void create(User user) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, user.getName());
statement.setString(2, user.getPassword());
statement.setString(3, user.getEmail());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
user.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating user failed, no ID obtained.");
}
}
}
}
Note that you're dependent on the JDBC driver as to whether it works. Currently, most of the last versions will work, but if I am correct, Oracle JDBC driver is still somewhat troublesome with this. MySQL and DB2 already supported it for ages. PostgreSQL started to support it not long ago. I can't comment about MSSQL as I've never used it.
For Oracle, you can invoke a CallableStatement with a RETURNING clause or a SELECT CURRVAL(sequencename) (or whatever DB-specific syntax to do so) directly after the INSERT in the same transaction to obtain the last generated key. See also this answer.
Create Generated Column
String generatedColumns[] = { "ID" };
Pass this geneated Column to your statement
PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
Use ResultSet object to fetch the GeneratedKeys on Statement
ResultSet rs = stmtInsert.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println("Inserted ID -" + id); // display inserted record
}
When encountering an 'Unsupported feature' error while using Statement.RETURN_GENERATED_KEYS, try this:
String[] returnId = { "BATCHID" };
String sql = "INSERT INTO BATCH (BATCHNAME) VALUES ('aaaaaaa')";
PreparedStatement statement = connection.prepareStatement(sql, returnId);
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating user failed, no rows affected.");
}
try (ResultSet rs = statement.getGeneratedKeys()) {
if (rs.next()) {
System.out.println(rs.getInt(1));
}
rs.close();
}
Where BATCHID is the auto generated id.
I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:
private int insertQueryReturnInt(String SQLQy) {
ResultSet generatedKeys = null;
int generatedKey = -1;
try {
Statement statement = conn.createStatement();
statement.execute(SQLQy);
} catch (Exception e) {
errorDescription = "Failed to insert SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
try {
generatedKey = Integer.parseInt(readOneValue("SELECT ##IDENTITY"));
} catch (Exception e) {
errorDescription = "Failed to get ID of just-inserted SQL query: " + SQLQy + "( " + e.toString() + ")";
return -1;
}
return generatedKey;
}
This blog post nicely isolates three main SQL Server "last ID" options:
http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.
Instead of a comment, I just want to answer post.
Interface java.sql.PreparedStatement
columnIndexes « You can use prepareStatement function that accepts columnIndexes and SQL statement.
Where columnIndexes allowed constant flags are Statement.RETURN_GENERATED_KEYS1 or Statement.NO_GENERATED_KEYS[2], SQL statement that may contain one or more '?' IN parameter placeholders.
SYNTAX «
Connection.prepareStatement(String sql, int autoGeneratedKeys)
Connection.prepareStatement(String sql, int[] columnIndexes)
Example:
PreparedStatement pstmt =
conn.prepareStatement( insertSQL, Statement.RETURN_GENERATED_KEYS );
columnNames « List out the columnNames like 'id', 'uniqueID', .... in the target table that contain the auto-generated keys that should be returned. The driver will ignore them if the SQL statement is not an INSERT statement.
SYNTAX «
Connection.prepareStatement(String sql, String[] columnNames)
Example:
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
Full Example:
public static void insertAutoIncrement_SQL(String UserName, String Language, String Message) {
String DB_URL = "jdbc:mysql://localhost:3306/test", DB_User = "root", DB_Password = "";
String insertSQL = "INSERT INTO `unicodeinfo`( `UserName`, `Language`, `Message`) VALUES (?,?,?)";
//"INSERT INTO `unicodeinfo`(`id`, `UserName`, `Language`, `Message`) VALUES (?,?,?,?)";
int primkey = 0 ;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL, DB_User, DB_Password);
String columnNames[] = new String[] { "id" };
PreparedStatement pstmt = conn.prepareStatement( insertSQL, columnNames );
pstmt.setString(1, UserName );
pstmt.setString(2, Language );
pstmt.setString(3, Message );
if (pstmt.executeUpdate() > 0) {
// Retrieves any auto-generated keys created as a result of executing this Statement object
java.sql.ResultSet generatedKeys = pstmt.getGeneratedKeys();
if ( generatedKeys.next() ) {
primkey = generatedKeys.getInt(1);
}
}
System.out.println("Record updated with id = "+primkey);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
I'm using SQLServer 2008, but I have a development limitation: I cannot use a new driver for it, I have to use "com.microsoft.jdbc.sqlserver.SQLServerDriver" (I cannot use "com.microsoft.sqlserver.jdbc.SQLServerDriver").
That's why the solution conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) threw a java.lang.AbstractMethodError for me.
In this situation, a possible solution I found is the old one suggested by Microsoft:
How To Retrieve ##IDENTITY Value Using JDBC
import java.sql.*;
import java.io.*;
public class IdentitySample
{
public static void main(String args[])
{
try
{
String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs";
String userName = "yourUser";
String password = "yourPassword";
System.out.println( "Trying to connect to: " + URL);
//Register JDBC Driver
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
//Connect to SQL Server
Connection con = null;
con = DriverManager.getConnection(URL,userName,password);
System.out.println("Successfully connected to server");
//Create statement and Execute using either a stored procecure or batch statement
CallableStatement callstmt = null;
callstmt = con.prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT ##IDENTITY");
callstmt.setString(1, "testInputBatch");
System.out.println("Batch statement successfully executed");
callstmt.execute();
int iUpdCount = callstmt.getUpdateCount();
boolean bMoreResults = true;
ResultSet rs = null;
int myIdentVal = -1; //to store the ##IDENTITY
//While there are still more results or update counts
//available, continue processing resultsets
while (bMoreResults || iUpdCount!=-1)
{
//NOTE: in order for output parameters to be available,
//all resultsets must be processed
rs = callstmt.getResultSet();
//if rs is not null, we know we can get the results from the SELECT ##IDENTITY
if (rs != null)
{
rs.next();
myIdentVal = rs.getInt(1);
}
//Do something with the results here (not shown)
//get the next resultset, if there is one
//this call also implicitly closes the previously obtained ResultSet
bMoreResults = callstmt.getMoreResults();
iUpdCount = callstmt.getUpdateCount();
}
System.out.println( "##IDENTITY is: " + myIdentVal);
//Close statement and connection
callstmt.close();
con.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
try
{
System.out.println("Press any key to quit...");
System.in.read();
}
catch (Exception e)
{
}
}
}
This solution worked for me!
I hope this helps!
You can use following java code to get new inserted id.
ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
ps.setInt(1, quizid);
ps.setInt(2, userid);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
lastInsertId = rs.getInt(1);
}
It is possible to use it with normal Statement's as well (not just PreparedStatement)
Statement statement = conn.createStatement();
int updateCount = statement.executeUpdate("insert into x...)", Statement.RETURN_GENERATED_KEYS);
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
return generatedKeys.getLong(1);
}
else {
throw new SQLException("Creating failed, no ID obtained.");
}
}
Most others have suggested to use JDBC API for this, but personally, I find it quite painful to do with most drivers. When in fact, you can just use a native T-SQL feature, the OUTPUT clause:
try (
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(
"""
INSERT INTO t (a, b)
OUTPUT id
VALUES (1, 2)
"""
);
) {
while (rs.next())
System.out.println("ID = " + rs.getLong(1));
}
This is the simplest solution for SQL Server as well as a few other SQL dialects (e.g. Firebird, MariaDB, PostgreSQL, where you'd use RETURNING instead of OUTPUT).
I've blogged about this topic more in detail here.
With Hibernate's NativeQuery, you need to return a ResultList instead of a SingleResult, because Hibernate modifies a native query
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id
like
INSERT INTO bla (a,b) VALUES (2,3) RETURNING id LIMIT 1
if you try to get a single result, which causes most databases (at least PostgreSQL) to throw a syntax error. Afterwards, you may fetch the resulting id from the list (which usually contains exactly one item).
In my case ->
ConnectionClass objConnectionClass=new ConnectionClass();
con=objConnectionClass.getDataBaseConnection();
pstmtGetAdd=con.prepareStatement(SQL_INSERT_ADDRESS_QUERY,Statement.RETURN_GENERATED_KEYS);
pstmtGetAdd.setString(1, objRegisterVO.getAddress());
pstmtGetAdd.setInt(2, Integer.parseInt(objRegisterVO.getCityId()));
int addId=pstmtGetAdd.executeUpdate();
if(addId>0)
{
ResultSet rsVal=pstmtGetAdd.getGeneratedKeys();
rsVal.next();
addId=rsVal.getInt(1);
}
If you are using Spring JDBC, you can use Spring's GeneratedKeyHolder class to get the inserted ID.
See this answer...
How to get inserted id using Spring Jdbctemplate.update(String sql, obj...args)
If you are using JDBC (tested with MySQL) and you just want the last inserted ID, there is an easy way to get it. The method I'm using is the following:
public static Integer insert(ConnectionImpl connection, String insertQuery){
Integer lastInsertId = -1;
try{
final PreparedStatement ps = connection.prepareStatement(insertQuery);
ps.executeUpdate(insertQuery);
final com.mysql.jdbc.PreparedStatement psFinal = (com.mysql.jdbc.PreparedStatement) ps;
lastInsertId = (int) psFinal.getLastInsertID();
connection.close();
} catch(SQLException ex){
System.err.println("Error: "+ex);
}
return lastInsertId;
}
Also, (and just in case) the method to get the ConnectionImpl is the following:
public static ConnectionImpl getConnectionImpl(){
ConnectionImpl conexion = null;
final String dbName = "database_name";
final String dbPort = "3306";
final String dbIPAddress = "127.0.0.1";
final String connectionPath = "jdbc:mysql://"+dbIPAddress+":"+dbPort+"/"+dbName+"?autoReconnect=true&useSSL=false";
final String dbUser = "database_user";
final String dbPassword = "database_password";
try{
conexion = (ConnectionImpl) DriverManager.getConnection(connectionPath, dbUser, dbPassword);
}catch(SQLException e){
System.err.println(e);
}
return conexion;
}
Remember to add the connector/J to the project referenced libraries.
In my case, the connector/J version is the 5.1.42. Maybe you will have to apply some changes to the connectionPath if you want to use a more modern version of the connector/J such as with the version 8.0.28.
In the file, remember to import the following resources:
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mysql.jdbc.ConnectionImpl;
Hope this will be helpful.
Connection cn = DriverManager.getConnection("Host","user","pass");
Statement st = cn.createStatement("Ur Requet Sql");
int ret = st.execute();

can't retrieve data from database

Problem was:
Can't get just inserted data from the table. From the error message it looks like it doesn't see the first column. I know the column is there and data was inserted. I checked database. I checked if column Number has some hidden space in name. No it doesn't.
Tried:
Debugged every line and everything was good together with inserting data to database.
Found the issue is almost at the end of the code:
rs1.next();
String s1 = rs1.getString(1);
I tried to write
rs1.first();
String s1 = rs1.getString(1);
or
rs1.first();
String s1 = rs1.getString("Number");
Below I posted my final code that is working correctly and I am able to insert data to the table and display on the browser.
package mypackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.LinkedList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/query")
public class CList {
private LinkedList<SMember> contacts;
public CList() {
contacts = new LinkedList();
}
#GET
#Path("/{CList}")
public Response addCLocation(#QueryParam("employeeId") String eId) throws SQLException{
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
PreparedStatement ps0 = null, ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try{
//Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
//Connection variables: dbPath, userName, password
con = (Connection)
DriverManager.getConnection(dbURL,"someusername","somepassword");
System.out.println("We are connected to database");
//SQL Statement to Execute
System.out.print(id);
s = con.prepareStatement("SELECT 1 FROM CList WHERE Number=?");
s.setString(1, eId);
rs = s.executeQuery();
//Parse SQL Response
if(!rs.next()) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) " +
"VALUES (?,?,?,?)");
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhone());
ps.executeUpdate();
ps = con.prepareStatement("SELECT Number, First_Name,
Last_Name, Phone_Number FROM CList
WHERE Number=" + eId);
rs1 = ps.executeQuery();
while(rs1.next()){
result = "[Added contact to contact list.
Number: " + rs1.getString(1) +
"][First_Name: " + rs1.getString(2) +
"][Last_name: " + rs1.getString(3) +
"][Phone_Number: " + rs1.getString(4) +
"]\n";
}
}
else {
result = "[Contact is already on the list]";
}
}
catch(Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
//Close Database Connection
ps0.close();
ps.close();
con.close();
}
}
catch(Exception e) {
System.out.println(e);
}
//Return the Result to Browser
return Response.status(1000).entity(result).build();
}
Table
1234 number is unique and it is a number I want to get.
You see number should be unique. So far I am taking data from the SMember class and it always insers the same data. Purpose of my question is just to ge the information I inserted few seconds ago.
Also, there is SMember class that I didn't post here and in its constructor I initialize number, first name, last name, and phone number. Testing purpose.
I made all recommended changes but problem remains the same.
There is several issues here.
The solution to your question is that you do not let the database generate keys, that is why you cannot ask for the generated keys later.
Look at this line of your code:
ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name, Phone_Number) VALUES ('"+sm.getEmployeeID()+"', '"+sm.getFirstName()+"', '"+sm.getLastName()+"', '"+sm.getPhone()+"')", Statement.RETURN_GENERATED_KEYS);
You later want to retrieve the Number column's value as a generated key. You however do pass a value for that column, namely the return value of sm.getEmployeeID(). If you pass a value, it will not get generated (assuming that this column is defined in database as being auto incremented.
Fixing this however, will not solve everything as your code has quite a lot of issues. Let me list the ones I can directly spot:
You initialize your variable sm by creating a new object. But you will still not have values for employee id, first name, last name or phone number as you nowhere set those values to sm (or do you do that in the default constructor?).
You are trying to use a prepared statement, this is good, but you are actually not doing that, this is very bad as it openes the ground for SQL injection. Instead of creating the query string like you are doing, you should use a fixed string like e.g INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?) and then set the values on the statement before executing it. That way nobody can mess with your database through that statement (read up on SQL injection, just google it to see the issue you would introduce).
Your employee id seems to be the eId parameter of your method. You should use that also in your select statement to see if it is already in your database (use a prepared statement here also) and in your insert statement later when the id is not already in the database.
If you are checking for a specific id, then insert that specific id, it is quite useless to retrieve some generated id. You already have defined your unique identifier. Use that one!
Edit: As your code is kind of a mess, I have cleaned this stuff a bit and fixed the issues that I could directly find. Check if this is helping you:
public Response addCLocation(String eId) throws SQLException {
String dataSourceName = "DBname";
String dbURL = "jdbc:mysql://localhost:3306/" + dataSourceName;
String result = "";
Connection con = null;
Statement s = null;
PreparedStatement ps = null;
ResultSet rs = null, rs1 = null;
String id = eId;
try {
try {
// Database Connector Driver
Class.forName("com.mysql.jdbc.Driver");
// Connection variables: dbPath, userName, password
con = DriverManager.getConnection(dbURL, "someusername", "somepassword");
System.out.println("We are connected to database");
s = con.createStatement();
// SQL Statement to Execute
System.out.print(id);
PreparedStatement alreadyThere = con.prepareStatement("SELECT 1 FROM CList WHERE Number = ?");
alreadyThere.setString(1, eId);
System.out.println("0");
// Parse SQL Response
int i = 0;
if (rs.next() == false) {
SMember sm = new SMember();
ps = con
.prepareStatement("INSERT INTO Contact_List (Number, First_Name, Last_Name, Phone_Number) VALUES (?,?,?,?)");
ps.setString(1, sm.getEmployeeID());
ps.setString(2, sm.getFirstName());
ps.setString(3, sm.getLastName());
ps.setString(4, sm.getPhone());
ps.executeUpdate();
}
else {
result = "[Contact is already on the list]";
}
}
catch (Exception e) {
System.out.println("Can not connect to database");
e.printStackTrace();
}
finally {
// Close Database Connection
s.close();
ps.close();
con.close();
}
}
catch (Exception e) {
System.out.println(e);
}
// Return the Result to Browser
return Response.status(200).entity(result).build();
}
You are getting this error because your first query is wrong it is returning an empty resultset.
Firstly,
rs = s.executeQuery("SELECT 1 FROM CList WHERE Number='id'");
the above line in your code is not correct it should be like this:
**rs = s.executeQuery("SELECT 1 FROM CList WHERE Number="+id);**
then the correct query will be fired to database.
Secondly,there is problem in following code
if(rs.next() == false) {
SMember sm = new SMember();
ps = (PreparedStatement) con.prepareStatement("INSERT
INTO CList (Number, First_Name, Last_Name,
Phone_Number) VALUES ('"+sm.getEmployeeID()+"',
'"+sm.getFirstName()+"', '"+sm.getLastName()+"',
'"+sm.getPhone()+"')",
Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
In the above code you should initialize the SMember, object currently in query they are going as null also the when you are using PreparedStatement you should use the query like this:
**ps = (PreparedStatement) con.prepareStatement("INSERT INTO CList (Number, First_Name, Last_Name,Phone_Number) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
ps.setString(1,sm.getEmployeeID());
ps.setString(2,sm.getFirstName());
ps.setString(3,sm.getLastName());
ps.setString(4,sm.getPhoneNumber());**
The Query statement maybe an issue "SELECT 1 FROM CList WHERE Number='id'",In select statement your id is taken as a String.we need to replace with value.
-->Try like this {"SELECT 1 FROM CList WHERE Number="+id},
-->One more thing "select 1 from table name" will print 1 for no of rows avail for your condition.
So my suggestion is
{"SELECT * FROM CList WHERE Number="+id}
try This!!
"SELECT 1 FROM CList WHERE Number='id'"
It looks like you're trying to actually select records where the Number value is 'id'. That may be causing the error when you try to do the "rs.next()" command on an empty result set. Are you instead trying to do something like
"SELECT 1 FROM CList WHERE Number=' " . id . "'"? Where "id" is a variable?

quotation marks in string parameter insert statement

Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.

Categories

Resources