I want to get the values from a table using db2 and print out the results.
This is the code I am trying to use to do that:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class connection {
public static void main(String[] argv) {
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Please include Classpath Where your DB2 Driver is located");
e.printStackTrace();
return;
}
System.out.println("DB2 driver is loaded successfully");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset=null;
boolean found=false;
try {
conn = DriverManager.getConnection("jdbc:db2:sabarish","db2admin","Murugasaranam");
if (conn != null)
{
System.out.println("DB2 Database Connected");
}
else
{
System.out.println("Db2 connection Failed ");
}
pstmt=conn.prepareStatement("SELECT * FROM SYSCAT.COLUMNS WHERE TABSCHEMA= 'STD' AND TABNAME= 'inventory'");
rset=pstmt.executeQuery();
if(rset!=null)
{
while(rset.next())
{
found=true;
System.out.println("Class Code: "+rset.getString("clcode"));
System.out.println("Name: "+rset.getString("name"));
}
}
if (found ==false)
{
System.out.println("No Information Found");
}
} catch (SQLException e) {
System.out.println("DB2 Database connection Failed");
e.printStackTrace();
return;
}
}
}
It only prints out column names. Instead of column names, what query statement can I use to get the results? db2 select * from store.inventory
does not seem to work as well.
Try select * from STD.inventory
Related
I have inserted my SQLite.db file inside of package named newpackage
Location of database file I inserted here isCollegeProject\src\operalogsapp\newpackage\SQLite.db
Now I want to get this database, so I want the correct format for inserting it to driver manager.
public class databaseConnection {
public static Connection con;
public static Connection getDBConnection(String username, String password, Integer portNumber, String serviceName){
try {
//Register the JDBC driver
System.out.println("before className");
Class.forName("org.sqlite.JDBC");
System.out.println(con==null);
System.out.println("Registered to the JDBC driver");
//Open the connection
if("V50700_HOTEL".equals(username) && "V50700_HOTEL".equals(password) && portNumber==1501 && "operal".equals(serviceName)){
con=DriverManager.getConnection("jdbc:sqlite:C:\\Users\\absasahu\\Documents\\db\\SQLite.db");
//inside the getConnection (above line) I want to get correct location of database to enter.
System.out.println("DriverManager connected to db");
}
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("Exception : "+ex);
//Logger.getLogger(dbCoonectionCode.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("DFHUDSBFSDF");
return con;
}
Any help will be appreciated.
"jdbc:sqlite:sqlite_database_file_path", in your case from your code:
"jdbc:sqlite:C:/Users/absasahu/Documents/db/SQLite.db"
Regarding your question using a relative path:
"jdbc:sqlite:SQLite.db"
See also the answers at Set path to a jdbc SQLite database, where it will be located
A complete example with class file and driver in the same directory (unfortunately on a unix machine):
// mkdir collegeproject
// cd collegeproject
// curl -LJO https://github.com/xerial/sqlite-jdbc/releases/download/3.36.0.3/sqlite-jdbc-3.36.0.3.jar
// javac SqliteTest.java
// java -classpath ".;sqlite-jdbc-3.36.0.3.jar" SqliteTest # in Windows
// java -classpath ".:sqlite-jdbc-3.36.0.3.jar" SqliteTest # in Unix
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteTest {
public static void main(String[] args)
{
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:sqltest.db");) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate("drop table if exists book");
statement.executeUpdate("create table book (id integer, title string)");
statement.executeUpdate("insert into book values(1, 'SQLite with JDBC for Beginners')");
try (ResultSet rs = statement.executeQuery("select * from book")) {
while (rs.next()) {
System.out.println("id = " + rs.getInt("id"));
System.out.println("title = " + rs.getString("title"));
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
}
$ javac SqliteTest.java
$ java -classpath ".:sqlite-jdbc-3.36.0.3.jar" SqliteTest
id = 1
title = SQLite with JDBC for Beginners
$
I am very new to Java and am simply trying to connect to my MSSQL database and return a list of customers. When I try the JDBC connection, I get a "no suitable driver found" error. When I add a Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") statement, I get a ClassNotFound error. This seems like it should be a lot easier than it's turning out to be. Please help me either find a suitable driver or how to get access through the Class.forName usage.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
public class DbConn {
public static String getConnString(){
return "jdbc:sqlserver://localhost\\SQLEXPRESS:1433;database=OhHold;";
}
public static void getConnection() {
try
{
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String user = "<USER>";
String pw = "****************";
Connection connection = DriverManager.getConnection(getConnString(), user, pw);
Statement statement = connection.createStatement();
String sql = "select txtCompanyName as company from tblCustomers where intNotActive <> 1";
ResultSet result = statement.executeQuery(sql);
while (result.next()) {
System.out.println(result.getString(1));
}
}
/*
// Handle any errors that may have occurred.
catch (ClassNotFoundException e) {
e.printStackTrace();
}
*/
catch (SQLException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
getConnection();
}
}
I've updated J/connector in my program from Connector 5.1.7 to Connector 5.1.39 and I saw selections stop working.
After digging more I realize that only ordered selects don't work. If I remove the order by from sql query everything is nice.
Here is my program
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MysqlVersion {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&character_set_server=utf8mb4&useSSL=false";
String user = "root";
String password = "root";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from `scripts` order by id desc");
//this returns false when order by is in the query
System.out.println(rs.next());
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Always System.out.println(rs.next()); will return false when 'order by' is in query.
If I go back to earlier version everything works ok. Am I doing something wrong. Is there a special setup I need to do? Or this is a bug?
I'm using MySql 5.7.14
This is my CreateQuery.java class .
package DbConnect;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CreateQuery {
Connection conn;
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new DbAccess().returnDatabaseConnection();
}
public int addNewLayertoDB(){
try {
PreparedStatement statement = null;
//String table_name = feature_name + "_" + shape;
String query = "SELECT the_geom from bbmp ";
statement = conn.prepareStatement(query);
//statement.setString(1, feature_name);
ResultSet rs = statement.executeQuery();
rs.close();
return 1;
} catch (SQLException ex) {
System.out.println("Sql exception");
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException{
CreateQuery cq = new CreateQuery();
cq.addNewLayertoDB();
cq.closeConn();
}
}
This is my DbConnect class
package DbConnect;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DbAccess{
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL " +
"JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/Ethermap","postgres", "*******");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null){
System.out.println("You made it, take control your database now!");
}else{
System.out.println("Failed to make connection!");
}
}
public Connection returnDatabaseConnection() {
System.out.println("DB not connected");
return null;
}
}
The error I am getting when I run CreateQuery is
DB not connected
Exception in thread "main" java.lang.NullPointerException
at DbConnect.CreateQuery.addNewLayertoDB(CreateQuery.java:24)
at DbConnect.CreateQuery.main(CreateQuery.java:45)
What is the error ? And How do I debug it ?
The method returnDatabaseConnection() that you call in the constructor of CreateQuery always returns null, so it's not a surprise that your connection object is null.
now I got some trouble connecting to my database. I know the tables i am looking for exist because when I access them with the command line they can be queried.
Probably some minor oversight but I would love some help.
This is where I make my connection to my database
package persistence;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class DBRegistry {
private static DBRegistry db = null;
private static Connection connection = null;
private DBRegistry() {};
public static synchronized DBRegistry getUniqueInstance() {
if (db == null) {
db = new DBRegistry();
return db;
}
else return db;
}
public synchronized Connection getDBConnection() {
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:src/database/taskMan.db");
return connection;
}
catch (SQLException e) {e.printStackTrace();}
catch (ClassNotFoundException e) {e.printStackTrace();}
return null;
}
public synchronized void closeConnection() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is how I query it
public void create(UUID oid, Object obj) {
Task t = (Task)obj;
String statement = "INSERT INTO `complexTask` (`oid`,`description`,`status`) VALUES (?, ?, ?)";
try {
PreparedStatement dbStatement = db.prepareStatement(statement);
dbStatement.setString(1, oid.toString());
dbStatement.setString(2, t.getDescription());
dbStatement.setBoolean(3, t.getStatus());
dbStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
and finally a stack trace:
java.sql.SQLException: no such table: complexTask
at org.sqlite.DB.throwex(DB.java:288)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:114)
at org.sqlite.PrepStmt.<init>(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at persistence.framework.ComplexTaskRDBMapper.create(ComplexTaskRDBMapper.java:23)
at persistence.PersistanceFacade.create(PersistanceFacade.java:49)
at persistence.persistanceStates.NewState.commit(NewState.java:10)
at persistence.PersistentObject.commit(PersistentObject.java:23)
at domain.objects.Task.commitToDB(Task.java:89)
at domain.TaskRepository.commitToDB(TaskRepository.java:60)
at domain.TaskController.persistanceCommit(TaskController.java:97)
at presentation.TaskControlsJPanel$3.actionPerformed(TaskControlsJPanel.java:127)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2012)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2335)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:404)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:253)
at java.awt.Component.processMouseEvent(Component.java:6175)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:5940)
at java.awt.Container.processEvent(Container.java:2105)
at java.awt.Component.dispatchEventImpl(Component.java:4536)
at java.awt.Container.dispatchEventImpl(Container.java:2163)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4461)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4125)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4055)
at java.awt.Container.dispatchEventImpl(Container.java:2149)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4362)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:604)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:275)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:200)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:190)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:185)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:177)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:138)
And some JUnit code for good measure, the first test passes and the second fails with a similar error to the one above
package test.persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import persistence.DBRegistry;
import junit.framework.TestCase;
public class TestDBRegistry extends TestCase {
public void testDBRegistryConnection() {
Connection con = DBRegistry.getUniqueInstance().getDBConnection();
assertNotNull(con);
}
public void testTableQuery() throws SQLException {
Connection con = DBRegistry.getUniqueInstance().getDBConnection();
PreparedStatement dbStatement = con.prepareStatement("SELECT COUNT(*) FROM `singleTask`");
assertEquals("should be 1 for successful query", 1, dbStatement.executeQuery());
}
I notice that in both your unit test and your other code you are using back-ticks around the table name. In the latest version of sqlite, this is fine but in older versions it wasn't handled as well I believe. Can you try removing the ticks around the table name or maybe changing them to regular quotes rather than back-ticks?
If that doesn't solve it I would check to be absolutely sure that you are pointing to the correct db file. If you specify a filename that doesn't exist you won't get an error, it will simply create a new database there. I'm not sure what the "current directory" is under the context of your app or unit test but be sure it is pointing to where you think it is. To test this, you could change the db file name to foo.db, run the unit test, then search your machine for foo.db to see where it got created. That will tell you where your app is working off of.
I'm not sure your JDBC connection string is quite right. The connection string you use ends with taskMan.db, but your comment above implies that the name of the database file is taskManDb.db (note the extra Db).
It might not fix your problem with the SQL INSERT, but I don't care at all for your DBRegistry implementation. I'd write it like this:
package persistence;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBRegistry
{
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet resultSet)
{
try
{
if (resultSet != null)
{
resultSet.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Maybe your table is in a package. so you might have do something like
select * from Tasks.ComplextTask
('Tasks' being the package)
Now just try to find a file with the same name in c:\windows\system32 and you will find it. It tells to us that your path is not correct. Have a nice day;
Please Commit your Connection after created table and after insertion.