I am having this problem,
When I send an SQL query as an argument it gives error
when I use the same query directly in my java program it works fine.
MY SQL query when I send as an argument is as follow
Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
rs = stmt.executeQuery(sqlQery); // Select RATINGPERIOD from INVESTMENT.I1INVE Where INVESTMENTID = 100
and when I use it directly into my java program is as follow
try
{
// Load the driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
System.out.println("**** Loaded the JDBC driver");
// Create the connection using the IBM Data Server Driver for JDBC and SQLJ
con = DriverManager.getConnection (url, user, password);
// Create the Statement
stmt = con.createStatement();
System.out.println("**** Created JDBC Statement object");
// Execute a query and generate a ResultSet instance
rs = stmt.executeQuery("Select RATINGPERIOD from INVESTMENT.I1INVE where INVESTMENTID = 100");
while (rs.next()) {
delay = rs.getString("RATINGPERIOD");
System.out.println("size of list ="+delay);
}
}
Error log
com.ibm.db2.jcc.am.SqlException: [jcc][10103][10941][3.62.57] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null
at com.ibm.db2.jcc.am.fd.a(fd.java:660)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:120)
at com.ibm.db2.jcc.am.jn.a(jn.java:4129)
at com.ibm.db2.jcc.am.jn.a(jn.java:2875)
at com.ibm.db2.jcc.am.jn.a(jn.java:679)
at com.ibm.db2.jcc.am.jn.executeQuery(jn.java:663)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQL.sqlQuery(DatabaseSQL.java:46)
at com.profitsoftware.testing.utils.keywords.date.DatabaseSQLKeywords.executeSqlQuery(DatabaseSQLKeywords.java:18)com.
ok some more information, I have assigned sql query to a string in Java program and then compared it to the query(String) I was getting as argument in my java program and it gives false. which explain maybe when query is passed from RIDE to Java programm it changes somehow. any idea what happens there ?
Thanks in advance and sorry if it sounds a stupid question, I a new to this programming world.
oK, It started to work, actually I was missing something there, so type. My logic itself was good but it was typo that created the problem
--Sara
Related
I'm trying to execute a query using a PreparedStatement in Java.
I am getting error number 1064 when I try to execute my query (syntax error).
I have tested this in MySQL query browser with substituted values which works fine.
What's wrong with my code?
Here's the relevant code:
String query = "select MemberID, MemberName from members where MemberID = ? or MemberName = ?";
Connection conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, 2);
s.setString(2, "zen");
ResultSet rs = s.executeQuery(query);
Here's the exception I'm getting:
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 '? or MemberName
= ?' at line 1
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 '? or MemberName = ?' at line 1
MySQL doesn't understand the meaning of ? in the SQL query. It's indeed invalid SQL syntax. So somehow it's not been replaced by PreparedStatement. And guess what?
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(query); // Fail!
You're overridding the prepared query with the original query! You need to call the argumentless PreparedStatement#executeQuery() method instead of Statement#executeQuery(String).
PreparedStatement s = conn.prepareStatement(query);
s.setInt(1, intValue);
s.setString(2, strValue);
rs = s.executeQuery(); // OK!
Unrelated to the problem, your code is leaking resources. The DB will run out of them after several hours and your application will crash. To fix this, you need to follow the JDBC idiom of closing Connection, Statement and ResultSet in the finally block of the try block where they're been acquired. Check the JDBC basic tutorial for more detail.
If you look at the javadocs for Statement (the superclass of PreparedStatement), the method docs for executeQuery(String) and executeUpdate(String) say this:
Note: This method cannot be called on a PreparedStatement or CallableStatement.
That's what you are doing here: calling executeQuery(String) from Statement on a PreparedStatement object.
Now since the javadocs say that you "cannot" do this, actual behavior you get is unspecified ... and probably JDBC driver dependent. In this case, it appears that the MySQL driver you are using is interpreting this to mean that you are doing the update as a non-prepared statement, so that the ? tokens are NOT interpreted as parameter placeholder. That leads the server-side SQL parser to say "syntax error".
(It would be easier for programmers if a different unchecked exception was thrown by the MySQL driver if you did this; for example UnsupportedOperationException. However, the standard JDBC javadocs don't say what should happen in this situation. It is up to the vendor what their drivers will do.)
I am working on an JAVA app that evaluates the data and log sizes of all databases on an instance and mails a monthly report. I am currently working with SQLServer2014. I am using an SQL query that calculates the size of all databases by querying sys.master_files.
The problem is that when using JDBC to make the query, it returns the error:
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost"
I have tried connecting to particular databases and that works fine. Is there any way to do this query directly to sys.master_files using JDBC? Or is there a smarter way altogether to accomplish the same result?
Thanks
Your "No suitable driver found" error is simply due to a malformed connection URL. jdbc:microsoft:sqlserver is not valid.
As for connecting to an instance without specifying a particular database, this works fine for me:
// NB: no databaseName specified in the following
String connectionUrl = "jdbc:sqlserver://localhost;instanceName=SQLEXPRESS;integratedSecurity=true";
try (Connection conn = DriverManager.getConnection(connectionUrl)) {
String sql = "SELECT name FROM sys.master_files WHERE type_desc='ROWS' ORDER BY database_id";
try (
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Note that sys.master_files is a system view that is available in all databases, so AFAIK it doesn't matter what the current database (catalog) is when you call it.
I am trying to get Generated key from sequnce.(Using Servlets & Oracle10)
Following is my code:
query ="insert into TABLE_NAME(COL1,COL2,COL3) values(sysdate,?,SEQ_NAME.nextval)";
PreparedStatement pstmt = con.prepareStatement(query,new String[]{"COL3"}); //Getting error on this line
pstmt.setString(1,Str2);
pstmt.executeUpdate();
ResultSet keyset = pstmt.getGeneratedKeys();
if(keyset.next())
{
genKey = keyset.getString(1);
}
But I am getting the Exception:
java.sql.SQLException: Unsupported feature
Few days ago this code was working fine. So what might be the reason that this code is not working now? (I haven't changed the JDBC driver war file)
Thanks in advance.
Is there another way of getting the value generated by sequence in the query?
Download the latest JDBC drivers, I think you need at least the 10.2.0.1 drivers and the db also need to be 10.2+
http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc101040.html
or first get the sequence value
String sqlForSeq = "select SEQ_NAME.NEXTVAL from dual";
ResultSet rs = stmt.executeQuery(sqlForSeq);
if (rs.next()) {
logSeq = rs.getString("NEXTVAL");
}
my first time in eclipse and im trying to get some test data from my sql server,now the problem is i have setup a sql connection using ms jdbc drivers and it seems like it works but when i run my query from eclipse,i get
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name
'KategoriName'.
error.My query works fine in sql manager.What could be the problem?I'm adding the code below as well:
String connectionString = "jdbc:sqlserver://192.168.0.155;user=user;password=password";
Connection conn= DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs;
String sqlconn="select [KategoriName] from [FINSAT6G9].[TBL_Test] whereID=493";
rs = stmt.executeQuery(sqlconn);
String aa = rs.getString("KategoriName");
System.out.println(aa);
Cheers.
Try including the database name in the connection string as so:
String connectionString = "jdbc:sqlserver://192.168.0.155;user=user;password=password;databaseName=FINSAT6G9";
Because, obviously, the error is telling you that the KategoriName column doesn't exist which can only mean 2 things: You have a typo or you are attempting to get the data from the wrong place, either the wrong database or the wrong table.
I have been assigned a task at work but i'm a beginner in Java and Eclipse.
I have to re-use an existing programm and modify some parts of it.
The following part does'nt work:
private java.sql.Connection conn;
private final String sqlRequest = "select ... from ...";
//................
private void DBConnect(){
try {
// Load the driver
java.lang.Class.forName(jdbcdriver).newInstance();
// Connect to database
conn = java.sql.DriverManager.getConnection(jdbcURL,dbuser,dbpwd);
//................
private void search2() {
try {
// create SQL statement
java.sql.Statement stmt = conn.createStatement(); //my line 135
java.sql.ResultSet rs = execRequest(stmt,sqlRequest);
//................
The error message in eclipse is :
"java.lang.NullPointerException at mon_prog.search2(mon_prog.java:135)"
This part used to work before... so is the problem due to my JDK version? I have JDK7u2
Get the connection first ...using..
Connection conn = DriverManager.getConnection(connection string);
Your conn seems null.
Have a look into great Vogella tutorial on how to connect to MySQL database from java program (IDE neutral way): http://www.vogella.de/articles/MySQLJava/article.html
Example steps to connect to your database:
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement
.executeQuery("select * from FEEDBACK.COMMENTS");
Set breakpoints on the Class.forName() and getConnection() calls in DBConnect(), and on your line 135, then run it all through the debugger. I wouldn't be the least bit surprised if getConnection() doesn't get executed before you try to use the connection. (Been there, done that, got the source control commit.)
If that's not it, you may also want to double-check that you really don't have another variable that is shadowing your intended conn instance. "Go to definition" is very useful for this; just make sure you end up in the expected place.