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.
Related
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
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 have a Jbutton (GetDataFromDB) in a simple java application that is suppose to load the data from the database depicted in the path in the code below into a Jtable in the application.
Edited answer into code:
private void GetDataFromDBActionPerformed(java.awt.event.ActionEvent evt) {
Connection con;
ResultSet rs = null;
Statement stmt;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={MS Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
stmt = con.createStatement();
String query = null;
query = "select * from cost";
rs = stmt.executeQuery(query);
i = 0;
while (rs.next()){
i = i + 1;
jTable.getModel().setValueAt(rs.getString(1), i, 1);
jTable.getModel().setValueAt(rs.getString(2), i, 2);
}
rs.close();
stmt.close();
con.close();
} catch(Exception err){
System.out.println(err.getMessage());
}
}
When I press the button I get the following message in the run output window:
No suitable driver found for jdbc:odbc:Driver={Microsoft Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I have at the top of my code the import:
import java.sql.*;
I have also tried changing from "Microsoft Access Driver" to "MS Access Driver" but I get the same message in the run output window i.e.
No suitable driver found for jdbc:odbc:Driver={MS Access Driver (.mdb, .accdb)};Dbq=C:\Users\Bruger\Documents\Database11.accdb
I'm really thankful for all your help, input and feedback.
Depending on the driver and If you are pre JDK 6**!
You need to register the driver.
Try adding:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
So:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Users\\Bruger\\Documents\\Database11.accdb");
It's also worth mentioning you don't need to do this every time you get a connection, just once to make sure the class is loaded.
There are a lot of stackoverflow questions relating to this, but the reason for it is below:
Source - From The Java Tutorial:
In previous versions of JDBC, to obtain a connection, you first had to
initialize your JDBC driver by calling the method Class.forName. This
methods required an object of type java.sql.Driver. Each JDBC driver
contains one or more classes that implements the interface
java.sql.Driver. ... Any JDBC 4.0 drivers that are found in your class
path are automatically loaded. (However, you must manually load any
drivers prior to JDBC 4.0 with the method Class.forName.)
On a related and very important note.
I would also recommend looking up how to handle connections. External Resources like database connections and cursors are easy to leak if you are not familiar with them. Look up 'try finally blocks', or more recently in java 7+ 'try-with-resources'.
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 am using a MySQL DB and a Java JDBC client to access it.
I have a Table that contains session information. Each session is associated with a SessionToken. This token is a Base64 encoded String of a Hash of some of the session values. It should be unique. And is defined as varchar(50) in the db.
When I try to lookup a session by its token I query the database using an sql statement like this:
select SessionId, ClientIP, PersonId, LastAccessTime, SessionCreateTime from InkaSession where SessionToken like 'exK/Xw0imW/qOtN39uw5bddeeMg='
I have a UnitTest that tests this functionality, and it consistently fails, because the query does not return any Session, even tough, I have just written the session to the DB.
My Unit test does the following:
Create Connection via DriverManager.getConnection
Add a session via Sql Insert query
close the connection
create Connection via DriverManager.getConnection
look for the session via sql select
unit test fails, because nothing found
When I step through this UnitTest with the debugger and copy past the select sql that is about to be sent to the db into a mysql command line, it works fine, and I get the session row back.
I also tried to retrive an older session from the db by asking for an older SessionToken. This works fine as well. It only fails, if I ask for the SessionToken immediately after I inserted it.
All connections are on AutoCommit. Nevertheless I tried to set the Transaction Level to "Read Uncommited". This did not work either.
Has anyone any further suggestions?
This is typically caused by the connection not being committed between insert and select.
Did you basically do the following?
statement.executeUpdate("INSERT INTO session (...) VALUES (...)");
connection.commit();
resultSet = statement.executeQuery("SELECT ... FROM session WHERE ...");
Edit I tried the following SSCCE on MySQL 5.1.30 with Connector/J 5.1.7:
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/javabase", "root", null);
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO foo (foo) VALUES ('foo')");
resultSet = statement.executeQuery("SELECT id FROM foo WHERE foo = 'foo'");
if (resultSet.next()) {
System.out.println(resultSet.getLong("id"));
} else {
System.out.println("Not inserted?");
}
} finally {
SQLUtil.close(connection, statement, resultSet);
}
}
Works flawlessly. Maybe an issue with your JDBC driver. Try upgrading.
Solved: The two token strings where not identical. One of them had a couple of Zero bytes at the end. (Due to the encrypting and decrypting and padding...) The two strings where visually identical, but MySQL and Java both said, they where not. (And they where right as usual)