I need to connect to my SQL Anywhere 11 (Sybase) database using the JConnect(jConn3.jar) driver from sybase from my Java application. I have tried the documentation and contacted the technical support, but valid help has been naught :(. Also if anyone maybe knows how to connect to Crystal Reports XI using this driver, help would be greatly appreciated...
Make sure your jconn3.jar is on the classpath of your application. Then use your jdbc driver as following:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/coffeebreak";
conn = DriverManager.getConnection(url, "username", "password");
// Do your stuff
conn.close();
} catch (Exception ex) {
...
}
Your comment on my answer helped. We encountered this kind of problem too. Our project used the viewer in a JSP. The problem occured while drilling down our report.
When you open your report the first time, the viewer generates an identifier for your report. You have to store that in the session so when you drill down, you can use this identifier. This way, you indicate that it is still the same report and the viewer will use the same datasource.
Here is a piece of code, which should be clearer than text:
// Report viewer
CrystalReportViewer crystalViewer = new CrystalReportViewer();
// Key to store the report source
String reportSourceSessionKey = "anyKeyYouWant";
Object reportSource = null;
// Get the report name passed in parameter
String reportName = request.getParameter("report");
if (reportName != null) {
// Build your report
ReportClientDocument reportClientDoc = new ReportClientDocument();
// ...
// Store de report source
reportSource = reportClientDoc.getReportSource();
session.setAttribute(reportSourceSessionKey, reportSource);
// Close the report document
reportClientDoc.close();
} else {
reportSource = session.getAttribute(reportSourceSessionKey);
}
// Set the source of the viewer
crystalViewer.setReportSource(reportSource);
....
This solved our JNDI problem. Hope it does it for you.
Related
I have looked at every possible answer on this site, nothing quite covers the issue.
I followed a tutorial and tried using the Firefox SQLite Manager AND using the SQLite3 shell to create the same database.
public class DBConnector {
static Connection conn = null;
public static Connection connect()
{
try{
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\John\\Desktop\\database.db");
return conn;
}
catch(Exception e){
e.printStackTrace(System.out);
return null;
}
}
}
Whenever I run this i get:
java.sql.SQLException: path to 'C:\Users\John\Desktop\database.db': 'C:\Users\John\Documents\NetBeansProjects\JBook\C:' does not exist
I'm new enough to this to where I have no idea what the issue is.
Any help is greatly appreciated. And yes, I have looked at all of the other questions posted and tried using their answers, to no avail.
Thanks again
EDIT: A couple of the possible answers already listed have included to change the .db extension to .sqlite
This did NOT work.
Another simply showed how to use an absolute path, once again, I had that covered and it didn't work.
Another talked about JUnit test and some issue they were having which was irrelevant to what I am doing
Finally got the issue:
Copy the path you specified in notepad++ and set encoding to ansi and you will see some special character before C: which is causing issue .
conn = DriverManager.getConnection("jdbc:sqlite:‪C:\\Users\\ravi\\Desktop\\database.db");
conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\ravi\\Desktop\\database.db");
I need to develop an AWS Lambda Java function to retrieve some records from RDS MySQL database.
Should I use JDBC? Should I use the standard JDBC example:
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
Step 1:
login IAM console
roles -> create new roles
role name :lambda-vpc-execution-role
AWS service roles ->
a) Select aws lambda
b) Attach policy "AWSLambdaFullAccess"
Step 2:
Get code from https://github.com/vinayselvaraj/lambda-jdbc-sample (note this is maven project)
Right click on project select Run as --->5.maven build...
for goal provide name package shade:shade
Go to project folder and target/lamda-0.0.1-SNAPSHOT-shaded.jar
Step 3:
Login to lambda console(skip blueprint)
Create new lambda
name: time-test
a) runtime-java
b) upload .zip(.jar) file (target/lamda-0.0.1-SNAPSHOT-shaded.jar)
Provide package.class-name::myhandler -> Handler
Role -> lambda-vpc-exceution-role
vpc provide rds-vpc details (this should work in same vpc group)
Create function
In the Action drop down list select configure test event
result will shown down like this "Execution result: succeeded (logs)"
Yes, you need to use standard JDBC code in your lambda function class. The code you provided looks okay. There are a few more things you need to do when accessing RDS or any other RDBMS through a Lamda function -
Create a jar or a zip file for your Lambda function
Your zip file needs to have a lib folder in which your JDBC driver file goes. The Lambda function doc says this is one of the two standard ways, but it didn't work for me.
You can create a jar file in which the driver classes are put in. This works. The best way to do it is through the Maven Shade plugin, which extracts the JDBC drivers and packs the classes in one single jar file.
Setup the handler function and specify it at the time of Lambda deployment
Define execution role and VPC as needed.
Upload and publish your jar or zip file.
You can test the Lambda function through the console, and see the actual output in the CloudWatch logs.
You could use this kinda implementation:
public static DataSource getDataSource(){
Utils._logger.log("Get data source");
MysqlDataSource mysqlDs = null;
try{
mysqlDs = new MysqlDataSource();
mysqlDs.setURL('jdbc:msql://'+'url');
mysqlDs.setUser('user');
mysqlDs.setPassword('pwd');
Utils._logger.log("Object "+mysqlDs.getUrl()+" "+mysqlDs.getUser()+" ");
return mysqlDs;
}
catch(Exception e) {
Utils._logger.log("No se pudo abrir el archivo de properties");
e.printStackTrace();
}
return mysqlDs;
}
One thing I am particularly noticing in your codebase is that even when you use this Lambda function for connecting to the specific RDS you have, the hostname may not be the correct one for Amazon RDS.
It needs to be the endpoint of the RDS you are trying to connect to and your complete connection url would look something like this below -
//jdbc:mysql://hostname (endpoint of RDS):port/databasename
String url = "jdbc:mysql://"+dbHost+":3306/"+dbName;
Since those endpoints can change for different databases and servers, you can make them as environment variables within Lambda and refer using
String dbHost = System.getenv("dbHost");
String dbName = System.getenv("dbName");
for a much cleaner and stateless design that Lambda supports.
Hi I am new enough to java and I am trying to create a connection from it to my sql database. using Netbeans I managed to set up a connection easily enough. The issue is when I try to connect using my code I get driver not found. Is there something wrong with what I have?
//function to execute the insert update delete query
public void theQuery(String query){
Connection con = null;
Statement st = null;
try{
con = DriverManager.getConnection("jdbc:oracle:thin:#redwood.ict.ad.dit.ie:1521:pdb12c.ict.ad.dit.ie", "eocribin","");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null,"Query Executed");
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
you have to add oracle thin driver into your projects library and then restart the IDE to take notice of changes. Make sure that oracle's server is running when you run this code. Also check the username and password.
Java Persistence in netbeans is a much better option then using Oracle thin driver in your code. Because it saves much of your time typing and harcoding. JPA(Java Persistence API) allows you to easily add the oracle's thin driver from its menu and reduces much of your time. It is used in enterprise applications . You should try this and watch its tutorials on the following site.
These are called JPA tutorials.
http://www.programming-simplified.com
I am trying to access a database that is stored in the classpath. I have installed ucanaccess 3.0.0 and all the required .jars.
My project hierarchy:
:
Here is the code I have so far:
public void login()
{
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:ucanaccess:/database/theDB.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT Student_Number FROM User");
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It's a simple login screen and I'm just testing the connection to the databse on a button click. I understand that referencing an absolute file-path is not good, so I thought having the file in the classpath would be better.
I am getting the error
No suitable driver found for jdbc:ucanaccess:file:/C:/Users/Gandalf/workspace/FubbleApp/bin/database/theDB.accdb
So I think it must be the "/database/theDB.accdb" but I am not sure how to fix this issue.
Any help is appreciated. Thanks in advance
The path to the database file (.accdb or .mdb) that you provide in your connection URL must be either
an absolute path, or
a relative path from the current working directory that is in effect when your application is running, which in your case appears to be "C:/Users/Gandalf/workspace/FubbleApp/bin/".
If you want your application to automatically search the CLASSPATH for the database file you will need to either provide your own code to do that or include some third-party code to do the search for you.
I think that the accdb has to be outside of the jar file. and I'm saying this because jdbc is a protocol and you must be able to write in the db and writing in a db inside an archive you have to unarchive and archive the db again. I don't think you can do it easily... the solution is... relative to jar or absolute path. (in the same folder with the jar file)
I am beginner in Java application programming.
I've created a database application in Java. I use an MS access database with the JDBC-ODBC driver. My application's create-connection code is below:
private void connection() {
try {
String driverurl = "jdbc:odbc:dharti_data";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(driverurl,"","");
} catch (SQLException e) {
JOptionPane.showMessageDialog(frm,e.getSQLState(),"Database Access Error",JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage(),"Database Access Error",JOptionPane.ERROR_MESSAGE);
}
}
This code works perfectly, but this code uses a datasource name I declared in Control Panel > Administrative Tools > Data Sources (ODBC) > System DSN > Add Data Source, with a Microsoft Access Driver (*.mdb).
But when I run the application on another PC, it can't run and instead it generates a database error.
I know that I can declare a driver in Data Sources (ODBC) > System DSN, and then it will run. But I don't want to do this on every machine I run my application on. My application should be able to pick up the database connection automatically. How can I make my application not require a data-source name?
String filename = "C:/Lab/northwind.mdb"; // this the path to mdb file
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
Im not sure if I got this, but are you shipping the jdbc driver along with your application? It has to be in your classpath and needs to be deployed with your application.
You will have to programmatically modify these registry sections:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI and
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC
Ice Engineering offer a public domain api that allows you to do that. Beside jars it has a DLL that you have to ship with your application. It is fairly straight forward and will work.
In order to get a better idea of what you have to do, use regedit in order to see the values before installing anything, then install an ODBC database manually, finally compare the new values with the old.
I used the sun.jdbc.odbc.JdbcOdbcDriver to connect to a MS Access database. Have that in the same directory as the class file and it should work. Although it should come already installed in the Java SDK.
This is a sample of a practice program I made a while ago.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=(MS ACCESS DATABASE DIRECTORY)");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select f_name, l_name from Test where f_name = 'Luke'"); // For example
// Iterate through the result and print the results
while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) );