Java SQLException on a string that runs in mysql - java

I am trying to make an inserction of a cliente.
When I print the string from the executeUpdate, copy and paste on mysql, the data is inserted with no problem.
The Exception has the follow description:
Exception in thread "main" 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 'update cliente set honorarioMensal = 2000.2 where cnpj = 'cnpj_ex'' at line 2
Can somebody help me?
public class Teste {
public static void main(String[] args) throws SQLException {
try {
Industria industria = IndustriaDB.getById(1);
System.out.println(industria);
Funcionario funcionario = new Funcionario("Func1","Func1");
funcionario.setCustoMensal(22);
Cliente cliente = new Cliente("cnpj_ex", "nome_ex",industria);
cliente.setPreco((float) 2000.2);
System.out.println(cliente);
System.out.println(cliente.getFuncionario());
ClienteDB.inserir(cliente);
ClienteDB.deletar(cliente);
} catch (ContexataException ge) {
System.out.println("---> " + ge.getMessage());
System.out.println("---> Detalhamento do erro: ");
ge.printStackTrace();
} finally {
}
}
}
public class ClienteDB extends Conexao{
public static void inserir(Cliente cliente) throws ContexataException, SQLException, NullPointerException {
Connection conn = Conexao.getConnection();
try {
String createString =
"INSERT into cliente "
+ "(cnpj, nome, id_Industria) "
+ "values('" + cliente.getCnpj() + "','"
+ cliente.getNome() + "',"
+ cliente.getIndustria().getId() + ");";
if (cliente.getFuncionario() != null){
createString = createString + "\n update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + "\n update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
System.out.println("SQL: " + createString);
executeUpdate(conn, createString);
System.out.println("Novo cliente inserido!\n");
// } catch (SQLException e) {
// throw new ContexataException("Erro ao inserir novo cliente.");
} catch (NullPointerException e) {
throw new ContexataException("Alguns dados não foram preenchidos suficientemente para o banco de dados!");
} finally {
Conexao.closeAll(conn);
}
}
public class Cliente { // only the atributes are necessary...
private String cnpj;
private String nome;
private float preco;
private Industria industria;
private Funcionario funcionario;
// getter and setter...

The problem is \n characters in the query string. You shouldn't use them, check your code and remove invalid characters.
if (cliente.getFuncionario() != null){
createString = createString + " update cliente set cpf_Funcionario = '" + cliente.getFuncionario().getCpf() + "' where cnpj = '" + cliente.getCnpj() + "';";
}
if (cliente.getPreco() != 0.0){
createString = createString + " update cliente set honorarioMensal = " + cliente.getPreco() + " where cnpj = '" + cliente.getCnpj() + "';";
}
And you can't writeupdate in the insert statements.

You cannot think about your problem like if you were typing the commands in a GUI. You must execute one executeUptade per statement rather than a batch of them. Of course also remove the ; at the end of the statement.
In fact GUIs probably will split your sql sentences and then send them one by one to SQL one by one.

Related

How to use question mark PreparedStatement (Java)?

I want to create a java source object in oracle database via JDBC, PreparedStatement. However, in the java source file, there are several question marks. Once I executed it, I faced an error message like below..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
I changed my code to be more understandable.
private void installOS_COMMAND() {
Connection targetDBconn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
pstmt = targetDBconn.prepareStatement(SQL);
pstmt.executeUpdate();
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (pstmt != null ) try {pstmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
Is there someone who can fix this problem?
Don't use prepared statements:
private void installOS_COMMAND() {
Connection targetDBconn = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
stmt.executeUpdate(SQL);
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}

Inserting records into an Oracle DB using Java

I am getting a missing comma error and I can't seem to figure out what could be causing it, any help would be appreciated.
Table create SQL:
CREATE TABLE APPOINTMENTS (APP_ID NUMBER(38) NOT NULL, I_ID NUMBER(38), DATE_TIME VARCHAR2(50), INSPECTION_TYPE VARCHAR2(30), PRICE VARCHAR2(10), HST VARCHAR2(10), TOTAL VARCHAR2(10), CLIENT_NAME VARCHAR2(40), CLIENT_NUMBER VARCHAR2(15), CLIENT_EXT VARCHAR2(10), CLIENT_EMAIL VARCHAR2(50), CLIENT_NAME2 VARCHAR2(40), CLIENT_NUMBER2 VARCHAR2(15), CLIENT_EXT2 VARCHAR2(10), CLIENT_EMAIL2 VARCHAR2(50), ADDRESS VARCHAR2(100), INTERSECTION VARCHAR2(100), CITY VARCHAR2(40), AGENT_ID NUMBER(38), REF_SOURCE VARCHAR2(30), BUILDING_TYPE VARCHAR2(30), SQUARE_FEET NUMBER(38), LIST_PRICE VARCHAR2(15), LOCKBOX VARCHAR2(40), VACANT VARCHAR2(10), NOTES VARCHAR2(255), BILL_TO VARCHAR2(20), PICTURES_REQUESTED VARCHAR2(10), FLAG VARCHAR2(10), APPROVED VARCHAR2(10), BUILDING_PREMIUM VARCHAR2(10), TRAVEL_PREMIUM VARCHAR2(10), SIZE_PREMIUM VARCHAR2(10), HOLIDAY_PREMIUM VARCHAR2(10), MISC_PREMIUM VARCHAR2(10), INSPECTOR_PAID VARCHAR2(10), COMPANY VARCHAR2(10) NOT NULL, SUGGESTED_RETAIL VARCHAR2(10), SUGGESTED_HST VARCHAR2(10), SUGGESTED_TOTAL VARCHAR2(10), PRIMARY KEY (APP_ID));
Java code to insert and execute:
dc.query = "INSERT INTO HR.APPOINTMENTS (APP_ID,I_ID, DATE_TIME,INSPECTION_TYPE, PRICE, HST, TOTAL, CLIENT_NAME, CLIENT_NUMBER, CLIENT_EXT, CLIENT_EMAIL,CLIENT_NAME2, "
+ "CLIENT_NUMBER2, CLIENT_EXT2, CLIENT_EMAIL2, ADDRESS, INTERSECTION, CITY, AGENT_ID, REF_SOURCE, BUILDING_TYPE, SQUARE_FEET, LIST_PRICE, LOCKBOX, VACANT,"
+ "NOTES, BILL_TO, PICTURES_REQUESTED, FLAG, APPROVED, BUILDING_PREMIUM, TRAVEL_PREMIUM, SIZE_PREMIUM, HOLIDAY_PREMIUM, MISC_PREMIUM, INSPECTOR_PAID,"
+ "COMPANY, SUGGESTED_RETAIL, SUGGESTED_HST, SUGGESTED_TOTAL)"
+ ""
+ "VALUES (" + hNum + "," + inspector + ",'" + date1 + "','" + inspectionType + "','" + price + "','" + hst + "','" + total + "','" + clientName + "','" + clientNumber + "','"
+ clientExt + "','" + clientEmail + "','" + clientName2 + "','" + clientNumber2 + "','" + clientExt2 + "','" + clientEmail2 + "','" + address + "','" + cMIntersection
+ "','" + city + "'," + hNum2 + ",'" + rSource + "','" + bType + "', 1000 ,'" + listPrice + "','" + lockbox + "','" + vacant + "','" + sInformation + "','" + billTo + "','"
+ pRequested + "','" + flagged + "', 'No', 'No', '0' , '0', '0', '0', '0', 'No','" + company + "','" + suggestedPrice + "','" + suggestedhst + "','" + suggestedTotal + "')";
dc.rset = dc.stmt.executeQuery(dc.query);
Here is a more generic approach. You just need to worry about class Oracle below and perhaps add some new entries for Factory method as I only defined a couple for you.
I also coded the actual execute for your PreparedStatement in the Row class, however I never tested that far. Let me know if it works for you (Don't forget to set your database credentials and stuff) ...
import java.io.IOException;
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.ArrayList;
import java.util.List;
public class Oracle {
public static void main(String[] args) {
Row row = new Row("OWNERNAME", "TABLENAME");
row.setDummyValues();
// set your individual column values here as you debug ...
System.out.println( row.getPreparedStatement() );
// for(Column column : row.getColumns()) {
// System.out.println("[" + column.name + "][" + column.type + "][" + column.nullable + "[" + column.value + "]");
// }
}
}
class Column {
int position;
String name;
String type;
boolean nullable;
Object value;
public Column(ResultSet resultSet) throws SQLException {
position = resultSet.getInt("COLUMN_ID");
name= resultSet.getString("COLUMN_NAME");
type= resultSet.getString("DATA_TYPE");
nullable= resultSet.getBoolean("NULLABLE");
value = null;
}
}
class DummyValueFactory {
public static Object createDummyValue(String type, boolean nullable) {
Object value = null;
if(!nullable) {
if(type.contains("CHAR")) {
value = "ABC";
}
else if(type.contains("NUMBER")) {
value = new Integer("123");
}
else if(type.contains("TIMESTAMP")) {
value = new java.sql.Timestamp(System.currentTimeMillis());
}
else {
throw new RuntimeException("CANNOT BUILD A DUMMY VALUE FOR " + type);
}
}
return value;
}
}
class Row {
String owner;
String table;
List<Column> columns = new ArrayList<Column>();
public Row(String ownerName, String tableName) {
owner = ownerName;
table = tableName;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(getMetaDataQuery());
while(resultSet.next()) {
columns.add(new Column(resultSet));
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(resultSet != null) {
resultSet.close();
}
if(statement != null) {
statement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
statement = null;
connection = null;
}
}
}
public void setDummyValues() {
for(Column column: columns) {
column.value = DummyValueFactory.createDummyValue(column.type, column.nullable);
}
}
public List<Column> getColumns() {
return columns;
}
public Column getColumn(String columnName) {
Column foundColumn = null;
for(Column column: columns) {
if(column.name.equals(columnName)) {
foundColumn = column;
break;
}
}
return foundColumn;
}
public boolean setColumn(String columnName, Object value) {
boolean result = false;
for(Column column: columns) {
if(column.name.equals(columnName)) {
column.value = value;
result = true;
break;
}
}
return result;
}
private final String getMetaDataQuery() {
String SQLString = "SELECT COLUMN_ID,\n";
SQLString += " COLUMN_NAME,\n";
SQLString += " DATA_TYPE,\n";
SQLString += " NULLABLE\n";
SQLString += "FROM ALL_TAB_COLUMNS\n";
SQLString += "WHERE OWNER = '" + owner + "'\n";
SQLString += " AND TABLE_NAME = '" + table + "'\n";
SQLString += "ORDER BY COLUMN_ID";
return SQLString;
}
public String getPreparedStatement() {
int counter = 0;
String SQLString = "INSERT INTO " + owner + "." + table + "(\n";
for(Column column : columns) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t" + column.name + "\n";
}
SQLString += ") VALUES (\n";
counter = 0;
for(int index = 0; index < columns.size(); index++) {
if(counter++ > 0) {
SQLString += ", ";
}
SQLString += "\t?\n";
}
SQLString += ")";
return SQLString;
}
public void executeInsert() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String SQLString = getPreparedStatement();
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(SQLString);
for(int index = 0; index < columns.size(); index++) {
preparedStatement.setObject(index, columns.get(index).value);
}
preparedStatement.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(preparedStatement != null) {
preparedStatement.close();
}
if(connection != null) {
connection.close();
}
}
catch (SQLException e) {
preparedStatement = null;
connection = null;
}
}
}
private static final Connection getConnection() throws ClassNotFoundException, SQLException, IOException {
String user = "username";
String password = "password";
String server = "server";
int port = 1234;
String sid = "database";
Connection connection = null;
String url = "jdbc:oracle:thin:#" + server + ":" + port + ":" + sid;
Class.forName("oracle.jdbc.driver.OracleDriver");
java.util.Properties info = new java.util.Properties();
info.put ("user", user);
info.put ("password", password);
info.put ("useFetchSizeWithLongColumn", "true");
connection = DriverManager.getConnection(url, info);
return connection;
}
}

java.sql.SQLException: lock wait time out exceeded; try restarting transaction

Hi in my project i am have created 2 tables which was Role_header and Role_details tables.
And also Role_details table is referring to the Role_header table.
In my java class i have two method they are
insertRoleHeader(...) --> which will be called first and set conn.setAutoCommit(false).i didn't commit this because following this i want to insert role_details with multiple records in Role_details table. so i will call this method first, if any exceptions thrown. i have set this to rollback in catch.
insertRoleDetails(.....) --> this method will be called by forloop. each and every calling of this method i will commit. at that time i am getting error as java.sql.SQLException: lock wait time out exceeded; try restarting transaction.
my sample code is here:
public void insertHeader(RoleMasterSupport rMS) throws SQLException {
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_header( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"role_name, "+
"remarks) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+rMS.getsRoleName()+"', "
+ "'"+rMS.getsRemarks()+"') ";
stmt.executeUpdate(sql);
stmt.close();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}
public void insertDetails(RoleMasterSupport rMS, TableModel model) throws SQLException
{
for (int i = 0; i < model.getRowCount(); i++) {
dbop.insertDetail(rMS, rMS.getaLScreenNames().get(i),
rMS.getaLAdd().get(i), rMS.getaLView().get(i),
rMS.getaLModify().get(i), rMS.getaLDelete().get(i));
}
}
public void insertDetail(RoleMasterSupport rMS, String sScreenName, String sAdd, String sView, String sModify, String sDelete) throws SQLException
{
connectDB();
Statement stmt = null;
try {
roleMasterConn.setAutoCommit(false);
stmt = roleMasterConn.createStatement();
String sql = "insert into role_details( create_user, " +
"create_date, " +
"run_user, " +
"run_date, " +
"role_id, " +
"screen_name, " +
"modify_screen, " +
"add_screen, " +
"delete_screen, " +
"view_screen) " +
"values('"+Constants.sUserName+"', now(), "
+ "'"+Constants.sUserName+"', now(), "
+ "'"+rMS.getsRoleID()+"', '"+sScreenName+"', "
+ "'"+sModify+"', '"+sAdd+"', "
+ "'"+sDelete+"', '"+sView+"') ";
stmt.executeUpdate(sql);
roleMasterConn.commit();
} catch (SQLException e) {
roleMasterConn.rollback();
throw e;
}
}

SQL logic error or missing database in Blackberry programming

I am trying to insert data into a SQLite database from a blackberry. When I call the screen I also call a method to create the database:
boolean sdCardPresent = false;
public static Database sqliteDB;
URI uri;
public void createdatabase()
{
try{
Enumeration e = FileSystemRegistry.listRoots();
root = (String)e.nextElement();
Dialog.inform(root);
if(root.equalsIgnoreCase("sdcard/"))
{
sdCardPresent = true;
}
if(!sdCardPresent)
{
Dialog.inform("O seu dispositivo nao suporta este compartimento sem cartao de memoria, verifique se existe um SD card no seu dispositivo.");
UiApplication.getUiApplication().pushScreen(new Tab_Main());
}else{
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri);
Statement st = sqliteDB.createStatement("DROP TABLE IF EXISTS atms;CREATE TABLE atms " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS balcoes;CREATE TABLE balcoes " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS contactos;CREATE TABLE contactos " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" nome TEXT, " +
" numero_conta INTEGER);") ;
st.prepare();
st.execute();
st.close();
sqliteDB.close();
Dialog.inform("Status: Database was successfully created.");
//}
} catch (Exception e){
System.out.println(e.getMessage());
Dialog.inform("\n "+e);
//UiApplication.getUiApplication().popScreen(Screen);
}
}
After that I use some Editfields and other components to get the values. I call the method to insert the parameters and send the query:
public void insert_update(String query) {
try {
sqliteDB = DatabaseFactory.openOrCreate(uri);
Statement st = sqliteDB.createStatement(query);
//Statement statement = _db.createStatement(query);
st.prepare();
st.execute();
st.close();
Dialog.inform("Adicionado com sucesso!!!");
}
catch ( Exception e ) {
Dialog.inform(e+"");
}
}
For example when I call it with the query = "insert into contactos values (null,"a","1"); I get an exception. SQL logic error or missing database.
Try dropping the quotes around the third column value.
INSERT INTO contactos VALUES (null,"a", 1);
It's defined as an INTEGER.
numero_conta INTEGER
EDIT :
System.out.println(uri); // check if null, or different
if (uri == null) {
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
}
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri); // open again
Statement st = sqliteDB.createStatement(query);

error in java update

if (e.getSource() == btn_updt) {
try {
String str = "img";
int max_avail;
double price;
Frame f = new Frame();
Connection con;
DriverManager
.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:dsnproj", "", "");
Statement s = con.createStatement();
// int mno=Integer.parseInt(txt_contcno.getText());
price = Double.parseDouble(txt_price.getText());
max_avail = Integer.parseInt(txt_qty_avl.getText());
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',desc='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";
System.out.println(qry_up);
s.execute(qry_up);
System.out.println("updated");
// JOptionPane.showMessageDialog(f,
// "Updates Successfully : ","A plain message",JOptionPane.PLAIN_MESSAGE);
} catch (Exception ae) {
System.out.println(ae.getLocalizedMessage());
}
return result;
}
and i got error as:
update category set prod_name='jjhhj',desc='jjjh',photo='img',max_quan_avail=88,cur_price=99.0,per='piece' where p_name='brush' [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
please help me...
Since DESC is a keyword, you must surround it with [].
Use this for your query:
String qry_up = "update category set prod_name='"
+ txt_pro_nm.getText() + "',[desc]='"
+ txt_pro_desc.getText() + "',photo='" + str
+ "',max_quan_avail=" + max_avail + ",cur_price="
+ price + ",per='" + ch_weight.getSelectedItem()
+ "' where p_name='" + ch_pro_nm.getSelectedItem()
+ "'";

Categories

Resources