java.lang.ClassNotFoundException:net.ucanaccess.jdbc.ucanaccessDriver - jdbc

I'm beginner with java and using console to compile and run my programs. I'm trying to read data from MS Access .accdb file with ucanaccess driver. As i have added 5 ucanaccess files to C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext, but still getting Exception java.lang.ClassNotFoundException:net.ucanaccess.jdbc.ucanaccessDriver.
Here is my code.
import java.sql.*;
public class jdbcTest
{
public static void main(String[] args)
{
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://C:javawork/PersonInfoDB/PersonInfo.accdb";
Connection conctn = DriverManager.getConnection(url);
Statement statmnt = conctn.createStatement();
String sql = "SELECT * FROM person";
ResultSet rsltSet = statmnt.executeQuery(sql);
while(rsltSet.next())
{
String name = rsltSet.getString("name-");
String address = rsltSet.getString("address");
String phoneNum = rsltSet.getString("phoneNumber");
System.out.println(name + " " + address + " " + phoneNum);
}
conctn.close();
}
catch(Exception sqlExcptn)
{
System.out.println(sqlExcptn);
}
}
}

Please add JDBC driver jar to lib folder.
Download URL download jar

I tried the method mentioned by Gord in his post Manipulating an Access database from Java without ODBC and used eclipse instead of command line compile and run. Also to learn eclipse basics, i watched video tutorial https://www.youtube.com/watch?v=mMu-JlBrYXo.
Finally i was able to read my MS Access data base file from my java code.

Related

How to check for SQLite database file existence in Xamarin and create a new database file if there were no such a database?

I'm trying to write a method for checking SQLite file existence. I downloaded a Nuget package for SQLite functionalities named System.Data.SQLite.Core.
I wrote this code for the method:
string path = "ReportData.db";
private void Create_db()
{
if (!System.IO.File.Exists(path))
{
SQLiteConnection.CreateFile(path);
using (var sqlite = new SQLiteConnection(#"Data Source=" + path))
{
sqlite.Open();
string sql = "create table temp(date varchar(20),activity varchar(1000))";
SQLiteCommand command = new SQLiteCommand(sql, sqlite);
command.ExecuteNonQuery();
sqlite.Close();
}
}
}
I don't know where to create my SQLite database file. When I use this method in a button, the application goes into break mode and says:
System.UnauthorizedAccessException: 'Access to the path
"/ReportData.db" is denied.'
Please help me.

Query Oracle using .net core throws exception for Connect Identifier

I'm quite new to Oracle and never used that before, now, I'm trying to query an Oracle database from a .Net Core Web Application having nuget package oracle.manageddataaccess.core installed and using an alias as the Data Source but I'm receiving the following error:
If I use the full connection string the query will work correctly
ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, SqlNetOraConfig SNOConfig, Hashtable ObTnsHT, String instanceName, ConnectionOption CO)
at OracleInternal.Network.OracleCommunication.Resolve(String tnsAlias, ConnectionOption& CO)
at OracleInternal.ConnectionPool.PoolManager`3.ResolveTnsAlias(ConnectionString cs, Object OC)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
So, from a few links I could understand that there is a tsnnames.ora file which must contain the map between connect identifiers and connect descriptors. And that this file can be found at the machine on which the Oracle has been installed with the path ORACLE_HOME\network\admin.
Question is:
Does the alias name that I'm using in my connection string which reads as Data Source: <alias_name>; User ID=<user>; Password=<password> need to be specified in the tsnnames.ora file? I don't have access to the machine where the Oracle database resides on otherwise I would have checked it earlier.
Here's the code snippet for more info: connection string and query values are mocked out
public static string Read()
{
const string connectionString = "Data Source=TestData;User ID=User1;Password=Pass1";
const string query = "select xyz from myTable";
string result;
using (var connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
var command = new OracleCommand(query) { Connection = connection, CommandType = CommandType.Text };
OracleDataReader reader = command.ExecuteReader();
reader.Read();
result = reader.GetString(0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
return result;
}
Is this enough or something else needs to be added/changed in here? Or probably the issue is with the tsnNames.ora file which might not contain the alias name here?
Thanks in advance
For the Data source
Data Source=TestData;User Id=myUsername;Password=myPassword;
Your tnsnames.ora probably should have the below entry
TestData=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
Since
Data Source=TestData;User Id=myUsername;Password=myPassword;
is same as
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

.exe starts successfully with windows scheduler but not throws error on visualcron

Scripts works fine when I run the exe when I am logged into the machine. But when I schedule the .exe on VisualCron, it throws an exception. I tried the same .exe on windows scheduler, I am able to run the job.
Error details given below. How do I work around this issue. Please help.
Code:
using log4net;
using Microsoft.VisualStudio.TestTools.UITest.Common;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace SeleniumDocManager
{
class To_Run_IE
{
private static ILog log;
static void ConfigureLog4Net()
{
log4net.GlobalContext.Properties["applicationname"] = "Selenium";
log4net.Config.XmlConfigurator.Configure();
log = LogManager.GetLogger(System.Reflection.Assembly.GetExecutingAssembly().GetType());
}
static string CreateFileFolder()
{
//Environment.CurrentDirectory = "C:\\myCSharp\\mySelenium";
Environment.CurrentDirectory = "E:\\Jobs\\Visualcron\\QA\\myInfoCenter";
string foldername = Path.Combine(Environment.CurrentDirectory, DateTime.Now.ToString("yyyy-MM-dd"));
if (!Directory.Exists(foldername))
{
Directory.CreateDirectory(foldername);
}
return foldername;
}
static void Main(string[] args)
{
ConfigureLog4Net();
string todayFolder = CreateFileFolder();
string programOutputPath = Path.Combine(todayFolder, "ProgramOutput.txt");
IWebDriver driver = new InternetExplorerDriver();
using (System.IO.StreamWriter file = new System.IO.StreamWriter(programOutputPath, true))
{
file.WriteLine("Starting Test, page title is: " + driver.Title);
}
string outputpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Console.Write ("outputpath is :" + outputpath + " ");
log.Debug("Starting Test, page title is: " + driver.Title);
System.Console.WriteLine("Starting Test, page title is: " + driver.Title);
System.Console.WriteLine("Page source is: " + driver.PageSource);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("http://cf-qa-web01:100/Home/Attachments/B1C56889-54D6-E211-ACC3-0050569D4561");
System.Threading.Thread.Sleep(5000);
By byXpath = By.XPath("//select[#id='DocumentType']");
System.Threading.Thread.Sleep(5000);
new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists(byXpath));
IWebElement element = driver.FindElement(byXpath);
var selectElement = new SelectElement(element);
int options = selectElement.Options.Count;
System.Threading.Thread.Sleep(5000);
Screenshot s0 = ((ITakesScreenshot)driver).GetScreenshot();
System.Threading.Thread.Sleep(5000);
s0.SaveAsFile(Path.Combine(todayFolder, string.Format("{0}_{1:yyyy-MM-dd_HH-mm-ss}.jpeg", "Document_Manager_Initial_Screenshot", DateTime.Now)),
System.Drawing.Imaging.ImageFormat.Gif);
System.Threading.Thread.Sleep(2000);
try
{
Console.WriteLine(selectElement.Options[0].Text);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(programOutputPath, true))
{
file.WriteLine("Capture # " + selectElement.Options[0].Text);
}
string _getssName = selectElement.Options[0].Text;
//new SelectElement(driver.FindElement(byXpath)).SelectByIndex(0);
Console.WriteLine("Capturing " + "Select Document Type" + " dropdown screenshot");
System.Threading.Thread.Sleep(5000);
Screenshot sss = ((ITakesScreenshot)driver).GetScreenshot();
System.Threading.Thread.Sleep(5000);
sss.SaveAsFile(Path.Combine(todayFolder, string.Format("{0}_{1}_{2:yyyy-MM-dd_HH-mm-ss}.jpeg", " Select Document Type ", "dropdown", DateTime.Now))
Error Details:
Unhandled Exception: OpenQA.Selenium.UnhandledAlertException: Modal dialog present at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) at OpenQA.Selenium.Remote.RemoteWebDriver.GetScreenshot() at SeleniumDocManager.To_Run_IE.Main(String[] args) Exception in Task: Non zero exit code
By default, all Tasks are executed in the background by the VisualCron service, normally running as SYSTEM account. If, for some reason, your executable tries to show an interface it will block the system as there is no desktop in the background to display or interact with the message.
You might want to know the reason why it throws the error. But if it works outside of VisualCron the cause is normally that you are not;
using a Credential
"Load profile" has not been checked in the Credential settings

error setting linkConfig.connectionString on sqoop 1.99.4

I followed https://sqoop.apache.org/docs/1.99.4/RESTAPI.html for trying out sqoop2. But Iam getting error "Exception in thread "main" org.apache.sqoop.common.SqoopException: MODEL_011:Input do not exist - Input name: linkConfig.connectionString" on the line linkConfig.getStringInput("linkConfig.connectionString").setValue("jdbc:mysql://localhost/my");
i tested sqoop2, mysql, database etc from terminal and working fine. please help. thanks in advance.
here is the code i am trying
import org.apache.sqoop.client.SqoopClient;
import org.apache.sqoop.model.MLink;
import org.apache.sqoop.model.MLinkConfig;
import org.apache.sqoop.validation.Status;
public class Sqoop2 {
public static void main(String[] args) {
//Initialization SqoopClient
String url = "http://<myip>:12000/sqoop/";
SqoopClient client = new SqoopClient(url);
// create a placeholder for link
long connectorId = 1;
MLink link = client.createLink(connectorId);
link.setName("Vampire");
link.setCreationUser("Buffy");
MLinkConfig linkConfig = link.getConnectorLinkConfig();
// fill in the link config values
linkConfig.getStringInput("linkConfig.connectionString").setValue("jdbc:mysql://<myip>/<dbname>");
linkConfig.getStringInput("linkConfig.jdbcDriver").setValue("com.mysql.jdbc.Driver");
linkConfig.getStringInput("linkConfig.username").setValue("root");
linkConfig.getStringInput("linkConfig.password").setValue("root");
// save the link object that was filled
Status status = client.saveLink(link);
if(status.canProceed()) {
System.out.println("Created Link with Link Id : " + link.getPersistenceId());
} else {
System.out.println("Something went wrong creating the link");
}
}
}
I faced the same issue. As per the documentation generic-jdbc connector id =1 and hdfs-connector id =2. But after we upgraded to 5.3.2 the id's were swapped.
Don't hard code the connector Id's(as said in the documentation). Use client.getConnectors(); or show connector --all method to look for existing connectors and get the connector Id you need. There is currently an issue logged for this https://issues.apache.org/jira/browse/SQOOP-1965.
Looks like connector 1 is already exists. Can you try with another id ?

Unable to connect to HP Quality Center using Com4j

OTAClient.dll version 10.0.0.2532
The following is the code I have used to connect to qc, apply filter and fetch qcpath and a field data. It is working fine with java 32 bit version 1.7.
import com.oracle.qcTasks.ClassFactory;
import com.oracle.qcTasks.IList;
import com.oracle.qcTasks.ISubjectNode;
import com.oracle.qcTasks.ITDConnection;
import com.oracle.qcTasks.ITDFilter;
import com.oracle.qcTasks.ITest;
import com.oracle.qcTasks.ITestFactory;
import com4j.Com4jObject;
public class qcClient {
public static void main(String[] args) {
ITest qcTestCase;
ISubjectNode qcTestCasePath;
Com4jObject SubjectField;
//QC url
String url = "http://fusionqc.us.oracle.com/";
//username for login
String username = "username";
//password for login
String password = "";
//domain
String domain = "domain";
//project
String project = "project";
ITDConnection itdc = ClassFactory.createTDConnection();
itdc.initConnectionEx(url);
itdc.connectProjectEx(domain, project, username, password);
boolean flag = itdc.connected();
System.out.println(itdc.projectName());
ITestFactory qcTestFactory = itdc.testFactory().queryInterface(ITestFactory.class);
ITDFilter qcFilter=qcTestFactory.filter().queryInterface(ITDFilter.class);
String query="^Subject\\path^";
qcFilter.clear();
qcFilter.filter("TS_SUBJECT", query);
IList qcTestList = qcFilter.newList();
for (Com4jObject com4jObject : qcTestList) {
qcTestCase = com4jObject.queryInterface(ITest.class);
System.out.println(qcTestCase.name());
System.out.println(qcTestCase.field("TS_USER_09"));
SubjectField = (Com4jObject)qcTestCase.field("TS_SUBJECT");
qcTestCasePath = SubjectField.queryInterface(ISubjectNode.class);
System.out.println(qcTestCasePath.path());
break;
}
System.out.println("command output :: "+flag);
System.out.println("OUT");
itdc.disconnectProject();
}
}
To the project requirement, I've downgraded the version of java to 64 bit version of 1.6. Post the downgrade, I'm receiving the following error.
Exception in thread "main" com4j.ExecutionException: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.ComThread.execute(ComThread.java:203)
at com4j.Task.execute(Task.java:25)
at com4j.COM4J.createInstance(COM4J.java:97)
at com4j.COM4J.createInstance(COM4J.java:72)
at com.oracle.qcTasks.ClassFactory.createTDConnection(ClassFactory.java:16)
at com.oracle.qcCode.qcClient.main(qcClient.java:32)
Caused by: com4j.ComException: 80040154 CoCreateInstance failed : Class not registered : .\com4j.cpp:153
at com4j.Native.createInstance(Native Method)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:117)
at com4j.COM4J$CreateInstanceTask.call(COM4J.java:104)
at com4j.Task.invoke(Task.java:51)
at com4j.ComThread.run0(ComThread.java:153)
at com4j.ComThread.run(ComThread.java:134)
I've found similar threads but didn't found any particular solution for the same. Please help. Is there any impact wrt java versions
What version of com4j do you use? See this post for using com4j on a 64 bit Windows machine. Are there any COM objects you can use from your 64 bit environment?
According to this blog entry you will get a Class not Registered Exception when you try to access a 32 bit COM object in a 64 bit environment. It even contains a workaround using some registry hacks. Maybe it works?

Resources