I'm trying to convert a MySQL stored procedure to java code. It's pretty simple SQL. It creates three temporary tables and then does a select based on them. However, I'm having trouble with SQLWarnings related to Data Truncation being thrown while creating the last temp table.
I'm not looking for an explanation of the warnings themselves. I was getting the same warnings during execution of the stored procedure (due to improperly formatted datetime fields), only there it didn't cause me any problems. In the java version, after Statement.executeUpdate() throws an SQLWarning, the temp table I was attempting to create doesn't exist.
How can I suppress the SQLWarnings? I'd prefer to be able to log a message noting the warning text, but I want my temp table to successfully be created as well.
My code looks something like this:
sqlStatement = "create temporary table mytemptable as (select ...) ;";
try {
stmt.executeUpdate(sqlStatement);
// Throws SQLWarning about Data Truncation
} catch (SQLWarning sqlW) {
logInfo("SQLWarning Caught: " + sqlW.getMessage());
}
stmt.executeQuery("select * from mytemptable ");
// Throws SQLException because mytemptable doesn't exist
To me it's a little strange but the equivalent of this worked:
create temporary table mytemptable ignore select ...;
This way, no exception is thrown by jdbc, but you can still call getWarnings() on the Statement object to get a list of warnings that were ignored.
Thanks Norbert van Nobelen for helping me figure this out in the comments of the OP.
Related
There is a select query that I am executing with DB2 JDBC. I am using Prepared Statement to pass in the value for the parameter. The column length of that parameter in the database is 12 so everything works fine until the length of the value is 12 and then it fails. Throws an exception with the error message as in the title. I did some searching and found an explanation in the following link http://www-01.ibm.com/support/docview.wss?uid=swg21319477 and the resolution mentioned in there is as below
Resolving the problem
Add additional client side validation code to prevents queries, with values that are larger than the allowed maximum length to be ran.
I don't want to do this. Why wouldn't the query just return back with no results. Any idea how do I go about this?
EDIT
String sql = "select student_id, student_name from student where student_id = ?";
try (Connection connection = DBUtils.GetConnection)
{
try (PreparedStatement statement = connection.prepareStatement(sql))
{
statement.setString(1, student_id);
ResultSet result = statement.executeQuery();
while (result.next())
{
//...
}
}
}
Even though I do not recommend doing it: We had a similar problem and found that - at least in our case -, if you really want that empty result, you can use a native SQL query instead of the prepared statement. Apparently, it is the argument binding for the prepared statement which runs into the argument validation. The native query (which you would have manually constructed using your arguments) seemed to sidestep this validation, and just returned an empty result.
(For completeness' sake: If really manually constructing your SQL query from given arguments, be sure to know what you are doing, validate your arguments, and specifically beware of SQL injection.)
The correct answer here would be what #Gaius Gracchus offers up as an alternative suggestion in his comment to #Hans's answer. You try/catch the SQLException, gather its SQL State (always better than an SQL Code), and handle/throw a custom exception to indicate invalid input to the client. An empty result set (even though that is what the OP desires) is not accurate. The only other real alternative is to increase the size of the column or procedural input/input-output (not likely).
try {
// sql bind or execute
}
catch (SQLException e) {
String sqlState = e.getSQLState();
if (sqlState != null && sqlState.equals("22001")) {
throw new CustomException("Invalid input, etc");
}
throw e;
}
I am using ojdbc6 jar and I want to use the In clause in a PreparedStatement.
I have used the createArrayOf(String,ArrayOfString) method of the connection object.
I got an error as Unsupported Feature
I have checked the PhysicalConnection class in the implementation for this method is
public Array createArrayOf(String s, Object aobj[]) throws SQLException {
SQLException sqlexception = DatabaseError.createUnsupportedFeatureSqlException();
sqlexception.fillInStackTrace();
throw sqlexception;
}
I have checked the ojdbc14.jar for this method. In that .jar file this method is not defined.
Please help me, which jar do I have to use? I want to implement the In clause functionality in the PreparedStatement.
So you want to do something like...
SELECT * FROM TAB WHERE ID IN ?
I had a similar problem in the past and tried all sorts of tricks with JDBC and Oracle (such as user defined types etc), but this is what we ended up with...
Create a global temporary table containing a single ID column (scoped to the session - ON COMMIT DELETE ROWS)
Start a transaction
Insert all of the Ids you want using a batch statement into the temp table
Join to this table to get the results, for example...
SELECT * FROM TAB T INNER JOIN MyTempTable X ON T.ID = X.ID
When you commit, the temp table is truncated
If you need to do several of these in the same transaction, be sure to delete form the temp table first.
(Also, we had loads of problems with driver versions and things like setArray etc, so we settled on this)
I am trying to make a select from a table, which works fine with every other table in my database, but when I try the following I recieve an error:
db.makeQuery("SELECT * FROM References");
Which calls:
public ResultSet makeQuery(String query) throws Exception
{
preparedStatement = connect.prepareStatement(query);
resultSet = preparedStatement.executeQuery(query);
return resultSet;
}
It then throws the following error:
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 'References' at line 1
I seems very strange to me, since this statement works:
db.makeQuery("select * from Products");
References is a keyword in SQL, so you better avoid it for table names. (See for instance this documentation.)
As suggested by Nishant, you can use reserved words in queries if you escape them with backticks.
Related question:
Using MySQL keywords in a query?
use
db.makeQuery("SELECT * FROM `References`");
if you can, better, avoid having names that are MySQL keywords. As suggested by aioobe
You might be misspelling the name of your table. MySQL gives this error when it can't find that table you're referring to.
Use SHOW TABLES; to see the names of the tables in your database, and double-check the name.
I am trying to use a Java application (which I do not have the source code for) to output the results of a call to a stored procedure into a text file.
This file works for other similar stored procedures in the system, but I can't seem to get it to produce anything for my new text file other than this exception:
ResultSet is from UPDATE: No Data
I've simplified the body of the stored procedure to a simple select 'Hello World!' and even that doesn't seem to be able to be written out.
Is there anything I can do within the stored procedure to produce results in a fashion that Java will accept?
I encountered this java.sql.SQLException. In my case I was running a query in this way:
String query =
"-- a classical comment " +
"select * " +
"from MYTABLE ";
ResultSet rs = conMain.createStatement().executeQuery(query);
while(rs.next()) {
//do something...
}
rs.next() throws the exception. The reason is that, due to the comments, query results to be:
"-- a classical comment select * from MYTABLE "
hence it's all commented... query is invalid! Many examples could be shown with this mistake (with the comment in the middle of the query etc.).
Solutions: add a \n at the end of each line of the query or use comments in the /*...*/ form.
I selected an older version of the driver an it worked for me.
http://dev.mysql.com/downloads/mirror.php?id=13598 (mysql-connector-java-5.0.8.zip)
I am working a Airsoft application.
I'm trying to add records to a MS Access Database via SQL in Java. I have established a link to the database, with the following:
try
{
//String Driver = "sun.java.odbc.JdbcOdbcDriver";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + URL,"","");
Statement stmt = conn.createStatement();
System.out.println("Connection Established!");
ResultSet rs = stmt.executeQuery("SELECT * FROM AirsoftGunRentals");
tblRent.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
I am using Ucanaccess to access my MS database. It is reading the database and is displaying to a JTable. However, I need to create three JButtons to add, delete and update the table. I have tried to code the add button, and I have tried to add a record, but it crashes and gives me errors.
try
{
//String Driver = "sun.java.odbc.JdbcOdbcDriver";
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://" + URL,"","");
Statement stmt = conn.createStatement();
System.out.println("Connection Established!");
String Query= "INSERT INTO AirsoftGunRentals(NameOfGun, Brand, TypeOfGuns, NumberOfMagazines,Extras,NumberAvailable,UnitRent)"+
"VALUES('"+pName+"','"+pBrand+"','"+pTypeOfGun+"','"+pNumMags+"','"+pExtras+"','"+pNumberAvail+"','"+pRent+"');";
ResultSet rs = stmt.executeQuery(Query);
JOptionPane.showMessageDialog(null, "Success!");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, "Error");
}
I have attempted all three, hoping for a result. But am still getting big errors. The only difference between the buttons is that one adds, one deletes and one updates the table. Other then that, the code is the same, minus variables.
As Brahim mentionned it, you should use stmt.executeUpdate(Query) whenever you update / insert or delete data. Also with this particular query, given your String concatenation (see end of line), there is no space between the ")" and the "VALUES" which probably causes a malformed query.
However, I can see from your code that you are not very experienced with such use-cases, and I'd like to add some pointers before all hell breaks loose in your project :
Use PreparedStatement instead of Statement and replace variables by placeholders to prevent SQL Injection.
The code that you are using here is extremely prone to SQL injection - if any user has any control over any of the variables, this could lead to a full database dump (theft), destruction of data (vandalism), or even in machine takeover if other conditions are met.
A good advice is to never use the Statement class, better be safe than sorry :)
Respect Java Conventions (or be coherent).
In your example you define the String Query, while all the other variables start with lower-case (as in Java Conventions), instead of String query. Overtime, such little mistakes (that won't break a build) will lead to bugs due to mistaking variables with classnames etc :)
Good luck on your road to mastering this wonderful language ! :)
First add a space before the quotation marks like this :
String Query= "INSERT INTO AirsoftGunRentals(NameOfGun, Brand, TypeOfGuns, NumberOfMagazines,Extras,NumberAvailable,UnitRent) "+
" VALUES('"+pName+"','"+pBrand+"','"+pTypeOfGun+"','"+pNumMags+"','"+pExtras+"','"+pNumberAvail+"','"+pRent+"');";
And use stmt.executeUpdate(Query); instead of : stmt.executeQuery(Query);in your insert, update and delete queries. For select queries you can keep it.
I managed to find an answer on how to add, delete and update records to a MS Access DB. This is what I found, after I declared the connection, and the prepped statement. I will try to explain to the best I can. I had to add values individually using this:
(pstmt = Prepped Statement Variable)
pstmt.setWhatever(1,Variable);
And it works fine now. I use the same method to delete and update records.
This is the basic query format:
String SQLInsert = "INSERT INTO Tbl VALUES(NULL,?,?,?,?)";
The NULL in the statement is the autonumber in the table. and .setWhatever() clause replaces the question marks with the data types. Thus manipulating the database.
Thank you everyone for all your contributions. It helped a lot, and made this section a lot more understandable.