To fetch database objects and data for other DB than default - java

We are working on Sybase database using Java JDBC. We are fetching some data and data objects from Sybase. Below code is used to get data :
Connection con = DriverManager.getConnection(sDBUrl, sUserName, sPassword);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(myQuery);
DriverManager.getConnection create and get connection for database url, user name and password given. Database Url format is : 192.123.111.15:5000?ServiceName=DATABASENAME
BUT there is no effect of database name given in getConnection, it always return database objects and its data for DEFAULT database set for the user.
What we need is : We need to get database objects and data from database name specified in DB url NOT default one.
How can we achieve this?

Related

ORA-00942: table or view does not exist error on writing to a table in database

I am trying to read a data from one database table using java + jdbc and trying to insert into another database table on different server in same session.
I have created 2 connection object(con,conn1), each pointing to correct database.
With 1st con object i am able to read the data but When it is going to write the data to another table using conn1 it is failing with error
ORA-00942- table or view doesnt exist.
I have also cross-checked that table is present and we can write to that table.
with a standalone class and static data i was able to write to that table.
Please let me know what is wrong in my approach.
Code sample:
public static void main
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection( "URL","uname","passwd");
//code to read from db and add to arraylist.
close resultset, con.
This connection obj points to new a database and url
Connection con1 = DriverManager.getConnection( "url","uname","passwd");
PreparedStatement pstmt = con1.prepareStatement("insert into SCHEMA_NAME.TABLE_NAME(columns) values(?,?,?,?,?,?,?,?)");
//code to iterate the arraylist populated above
pstmt.setint etc
pstmt.executeUpdate();
It fails after executeUpdate statement.
Yes, problem was with pstmt.setClob field. I changed it to pstmt.setString and took .toString() of clob object and it worked.
I m still puzzled why it throws table or view doesnt exist error.

OutputStream to the BLOB column of a DB2 database table

In a DB2 database, I have the following table:
CREATE TABLE MyTestTable
(
MYPATH VARCHAR(512) NOT NULL,
MYDATA BLOB,
CONSTRAINT MYTESTTABLE_PK PRIMARY KEY (MYPATH)
);
Using Java, I wish to update an existing row in this table with new blob data. My preferred way is to obtain an OutputStream to the BLOB column & write my data to the OutputStream.
Here is the test code I am using:
Connection connection = null;
PreparedStatement pStmnt = null;
ResultSet rSet = null;
try {
connection = ... // get db connection
String id = ... // set the MYPATH value
String sql = "SELECT MYDATA FROM MyTestTable WHERE MYPATH='"+id+"' FOR UPDATE";
pStmnt = connection.prepareStatement(sql);
rSet = pStmnt.executeQuery();
while (rSet.next()) {
Blob blobData = rSet.getBlob("MYDATA"); // this is a java.sql.Blob
OutputStream blobOutputStream = blobData.setBinaryStream(1);
blobOutputStream.write(data);
blobOutputStream.close();
connection.commit();
}
}
// close ResultSet/PreparedStatement/etc in the finally block
The above code works for the Oracle DB.
However, in DB2, calling setBinaryStream to get the OutputStream does not seem to work. The data does not get updated, and I do not get any error messages.
Qs: How can I get an OutputStream to the BLOB column of a DB2 table? What might need to be changed in the above code?
You are probably getting the data written to the Blob object successfully, but you need to do more with the PreparedStatement and ResultSet in order to actually update the value in the database.
First, your PreparedStatement must be instantiated using a version of Connection.prepareStatement() that takes a resultSetConcurrency parameter, which you must set to the value ResultSet.CONCUR_UPDATABLE. (I don't know that the SQL SELECT actually needs to specify the FOR UPDATE clause - see the tutorial at the link at the end of this answer.)
Second, after you close blobOutputStream, you need to update the value in the ResultSet using updateBlob(int columnIndex, Blob x) or updateBlob(String columnLabel, Blob x), then invoke ResultSet.updateRow() before doing a Connection.commit().
I haven't updated Blob values this way myself, but it should work. If you run into any issues trying to reuse the Blob originally read from the ResultSet (which you probably don't need to do if you're not actually using the original data), you can use Connect.createBlob() to make an empty one to start with. You can learn more about updating ResultSets from this tutorial.

how the command 'use database-name' is using java code

I would like to make o program that would store data from excel files in databases. I have plenty of databases so in my program i have to choose in which one I will store the data.
I have made the code to be able to connect mysql with my program and to show the available databases. What I would like to do now is to say in which database i would store the data.
To be more specific I would like the user first of all to see tha available databases in his client and afterwards he would have the chance to say in which database the data would be stored.
Could anyone help me how I would do this?
The code to see all the available databases is the below:
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/", "root", "root");
DatabaseMetaData meta = (DatabaseMetaData) con.getMetaData();
ResultSet res = meta.getCatalogs();
System.out.println("List of the databases: ");
while (res.next()){
System.out.println (" " +res.getString(1));
}
Thank you in advance!
I hope this SO link should help you . You can get all the data from the connection object
First do a create a simple connection
Connection con = (Connection) DriverManager.getConnection( "jdbc:mysql://localhost:3306/", "root", "root");
Look for an example here
see how he uses ResultSet Class to access the result.
Now,
retrieve information from information_schema.SCHEMATA so you can query like
SELECT schema_name FROM information_schema.SCHEMATA S;
to get all the schemas
Next after getting choice from user(maybe from console) you can set database according to uservalue using Connection#setCatalog()
If you want table information use this query
SELECT * FROM information_schema.TABLES T;
It would list all the tables in all schemas

Connect to a SQL Server database

I am trying to connect to a SQL Server database, but I don't really know how to go about it using the info I was given. I was given the following:
Provider
DataSource
Persist Security Info
User ID
Initial Catalog
I have always connected via a web address or something, so I didn't really know how to go about using this. I am attempting to do this is Java using JDBC.
See here a wide list of examples, depending on which version you're using:
SQL Server 2000
SQL Server 2005
SQL Server 2008
To connect to MSSQL Server from a Java application, you need to use the JDBC API. The JDBC API provides classes and methods that connect to the database, load the appropriate driver, send SQL queries, retrieve results etc.
HOW TO CONNECT TO THE DATABASE: A ‘Connection’ object represents a connection with a database. To establish the connection, use the method ‘DriverManager.getConnection’. This method takes a string containing a URL which represents the database we are trying to connect to. Below is the sample code for establishing a connection:
private String DATABASE_URL = "jdbc:odbc:embedded_sql_app"; // establish connection to database
Connection connection = DriverManager.getConnection( DATABASE_URL,"sa","123" );
Detailed discussion about the Database URL and how to create it can be found in the resource provided at the end of this post.
QUERYING THE DATABASE: The JDBC API provides three interfaces for sending SQL statements to the database, and corresponding methods in the ‘Connection’ interface create instances of them. 1. Statement - created by the ‘Connection.createStatement’ methods. A ‘Statement’ object is used for sending SQL statements with no parameters.
2. PreparedStatement - created by the ‘Connection.prepareStatement methods’. A ‘PreparedStatement’ object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
3. CallableStatement - created by the ‘Connection.prepareCall’ methods. ‘CallableStatement’ objects are used to execute SQL stored procedures from Java database applications.
RETRIEVING THE RESULT: A ‘ResultSet ‘is a Java object that contains the results of executing a SQL query. The data stored in a ‘ResultSet’ object is retrieved through a set of get methods that allows access to the various columns of the current row. The ‘ResultSet.next’ method is used to move to the next row of the ‘ResultSet’, making it the current row. The following code fragment executes a query that returns a collection of rows, with column ‘a’ as an ‘int’, column ‘b’ as a ‘String’, and column ‘c’ as a ‘float’:
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { // retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}
This is just a brief introduction on how to interact with a database from Java. For more details on the items discussed above as well as information on passing parameters, executing stored procedures etc. please refer to the following resource: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html#Shahriar_N_Embedding_SQL_in_Java ) Here, you will also find information on how to interact with a database programmatically; i.e. without using SQL. Hope you find this useful.
Source:
http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html

Excel DB: Operation must use an updateable query

for a jdbc program, im required to make a connection an excel database. the connection is successfully made but wen entering values into it, its giving an "Operation must use an updateable query" exception.
here s the code:
String url="jdbc:odbc:Sample"; //CHANGE THE DATABASE NAME
Connection conn= DriverManager.getConnection(url,"","");
PreparedStatement prepstat = null;
String insert="INSERT INTO [Sheet1$] ([AccountID], [ProjectID], [PositionID]) VALUES (?,?,?)";
prepstat= conn.prepareStatement(insert);
prepstat.setString(1, accountID);
prepstat.setString(2, projectID);
prepstat.setString(3, positionID);
prepstat.executeUpdate(); // this is where the exception occurs
Did you specifically state that the connection was readwrite in your connection string?
I am not familiar with JDBC, but ODBC would be:
"Driver={Microsoft Excel Driver (*.xls)};" & _
"DBQ=C:\MyFolder\MyWorkbook.xls; ReadOnly=False;"
Excel is read-only by default: http://support.microsoft.com/kb/257819
It was just needed to uncheck the read only while creating the DSN.

Categories

Resources