How do you define a stored procedure in java? - java

I've worked with web on asp.net C# defining connections with the following structure
try
{
sqlConnection = new SqlConnection(dbConnectionString);
SqlCommand command = new SqlCommand("sp_Test", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Id", SqlDbType.VarChar).Value = txtId.Text;
command.Parameters.Add("#Name", SqlDbType.DateTime).Value = txtName.Text;
sqlConnection.Open();
return command.ExecuteNonQuery();
sqlConnection.Close();
}
catch (SqlException ex)
{
Console.WriteLine("SQL MESSAGE Error" + ex.Message.ToString());
return 0;
}
...but I'm looking for its equivalent in java. The application I'm working on it is only local. I just need to connect my netbeans, the java IDE I'll use, to my ORACLE Database. The version of the database is Oracle 11g release 2. Thanks for the help!

Related

Moving a database in netbeans to another computer

I made a fairly small java program in netbeans, with the database saved in the scr folder under database/mainUserData, On my main pc, if i export it to a .jar folder, It works, If i copy all the data in the folder (70mb's worth) to another pc, it can't find the database any more, I made sure to add code that always uses the current directory in the jar folder as a url to the database, this is the connection code:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", "jacovanstryp", "Password1234");
Why is it when i move it to another computer (The whole file, it no longer knows where the database is?
What I have Tried:
URL url = this.getClass().getResource("/com/vanstryp/res/Database/MainUserData"); // This is the same directory as where the .jar is located
This just returns Null.
This is the top Error code it returns
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
This is the code for the method I used
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//This code will connect the database to the java program
//Information to connect database obtained from --> https://www.youtube.com/watch?v=c7RZV4VLv3s
Connection myconObj = null; //allows to connect to database
Statement mystatObj = null; // create statement (Execute queries)
ResultSet myresObj = null; // get result
ResultSetMetaData mymeta = null;
try {
String query = "select * from JACOVANSTRYP.MAINUSERDATA";
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData/");
myconObj = DriverManager.getConnection("jdbc:derby:/" + databaseLocation, "jacovanstryp", "Eduplex1234");
mystatObj = myconObj.createStatement();
myresObj = mystatObj.executeQuery(query);
mymeta = myresObj.getMetaData();
int colomnNo = mymeta.getColumnCount();
while (myresObj.next()) {
String dbUsername = myresObj.getString("Username");
String dbPassword = myresObj.getString("Password");
System.out.println();
if (username.equalsIgnoreCase(dbUsername) && password.equals(dbPassword)) {
PrintWriter activeUser = new PrintWriter(new FileWriter("activeUser.db"));
activeUser.println(dbUsername);
activeUser.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} catch
(ClassNotFoundException ex) {
Logger.getLogger(commonMethods.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
This line:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", ...);
uses a connection string of "jdbc:derby://localhost:1527/MainUserData". That means that you have setup (maybe through Netbeans) a Derby server on that computer listening on port 1527.
Copying a jar and the file backing the database is not enough: you must start the Derby server on the new host or use the one from the old host:
myconObj = DriverManager.getConnection("jdbc:derby://other.host.full.name:1527/MainUserData", ...);
Alternatively, you could use the embedded mode of Derby. Then you just have to declare which folder contains the database file:
myconObj = DriverManager.getConnection("jdbc:derby:/path/to/MainUserData", ...);
In this mode, you can just copy both the jar (and its optional other files) and the database to the new system, and it should find the database if you give a correct path.

How to parse Unicode java applications Vdurmont emoji-java2.0.1 library

I'm using netbeans IDE for developing java desktop application with Vdurmont emoji-java2.0.1 Emoji library. Its working with my netbeans IDE development and sent emojis unicode another side its working fine (Showing fine and correct emoji with emotions). Problem: When i clean build and make a .jar with all necessary lib,
it showing this (😡 and ?) on another side web app Vdurmont emoji-java2.0.1 library didn't load or not working with myemojiapp.jar file. *please let me know if any need for this ?..
Object finalmsz = "";
msz = jtp.getText();
MyHtml2Text parser = new MyHtml2Text();
try {
parser.parse(new StringReader(msz));
} catch (IOException ee) {
//handle exception my exp
}
finalmsz = Imoji.parseToUnicode(parser.getText() + str);**
public static String parseToUnicode(String input) {
String result = input;
for (Emoji emoji : EmojiManager.getAll()) {
result = result.replace(emoji.getHtmlHexidecimal(),emoji.getUnicode());
}
return result;
}
Please note this parsing not working with my myemojiapp.jar file (showing this 😡 and ?)
but it works fine on my netbeans during development.

Insert variables into SAS using JAVA (IOM Bridge). Should i use CORBA stubs and JDBC or is there any other alternative?

This is part of my code snippet
WorkspaceConnector connector = null;
WorkspaceFactory workspaceFactory = null;
String variableListString = null;
Properties sasServerProperties = new Properties();
sasServerProperties.put("host", host);
sasServerProperties.put("port", port);
sasServerProperties.put("userName", userName);
sasServerProperties.put("password", password);
Properties[] sasServerPropertiesList = { sasServerProperties };
workspaceFactory = new WorkspaceFactory(sasServerPropertiesList, null, logWriter);
connector = workspaceFactory.getWorkspaceConnector(0L);
IWorkspace sasWorkspace = connector.getWorkspace();
ILanguageService sasLanguage = sasWorkspace.LanguageService();
//send variable list string
//continued
I need to send the "variableListString" to the SAS server through IOM bridge. Java SAS API doesn't give explicit ways to do it. Using CORBA and JDBC is the best way to do it?? Give me a hint how to do it. Is there any alternative method to do it??
This was asked a while back but useful in case anyone is still looking to do the same.
One way to do this is build a string of sas code and submit it to the server. We use this method for setting up variables on the host for the connected session. You can also use this technique to include sas code using code like %include "path to my code/my sas code.sas";:
...continue from code in the question...
langService = iWorkspace.LanguageService();
StringBuilder sb = new StringBuilder();
sb.append("%let mysasvar=" + javalocalvar);
... more variables
try {
langService.Submit(sb.toString());
} catch (GenericError e) {
e.printStackTrace();
}

Java connect to OracleDB very slowly (with ojdbc6.jar and Linux)

I'm try to deploy the web services that have a connection to ORACLE database (10g).
Currently, I have
- CentOS 6.4 64bits
- Apache Tomcat 7.0.42 with JDK 1.7.0_25
- Ojdbc6.jar
When I calling web services with the same version of tomcat on Windows. It's working properly (0.1-0.5 Seconds/transaction).
but unfortunately, when I try to call it on CentOS server, It quite very slow (10-20 seconds/transaction)
The libraries are exactly same except the OS and as I monitoring catalina.out, there is no error but It's slowly when dbCreateConnection() was executed)
Please give me an advise.
Thanks :\
FYI, Here is the code in database section.
try {
Class.forName("oracle.jdbc.OracleDriver");
InputStream isr = this.getClass().getResourceAsStream("/"+"dbConfig.properties");
Properties prop = new Properties();
if (isr != null){
InputStreamReader isrProperties = new InputStreamReader(isr);
prop.load(isrProperties);
}
String dbURL = "jdbc:oracle:thin:#"+prop.getProperty("dbhost")+":"+prop.getProperty("dbport")+":"+prop.getProperty("dbname");
System.out.println("TRACE : getdbConfig --> "+dbURL);
String username = prop.getProperty("dbuser");
String password = prop.getProperty("dbpass");
dbConn = DriverManager.getConnection(dbURL, username, password);
if(dbConn != null){
System.out.println("TRACE : Connected to "+dbURL);
}
}
catch (SQLException ex) {
System.out.println("Error Message : getConnection Failed --> "+ex.getSQLState());
ex.printStackTrace();
}
Start Java with the JVM flag:
-Djava.security.egd=file:/dev/./urandom

Java - Create domain in Amazon SimpleDB

I'm working with Amazon SimpleDB and attempting the creation of a DB using the following tutorial . Basically it throws an error i.e. Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost. The full stacktrace is as below:
Error occured: java.lang.String cannot be cast to org.apache.http.HttpHost
java.lang.ClassCastException: java.lang.String cannot be cast to org.apache.http.HttpHost
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:416)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at com.xerox.amazonws.common.AWSQueryConnection.makeRequest(AWSQueryConnection.java:474)
at com.xerox.amazonws.sdb.SimpleDB.makeRequestInt(SimpleDB.java:231)
at com.xerox.amazonws.sdb.SimpleDB.createDomain(SimpleDB.java:155)
at com.amazonsimpledb.SDBexample1.main(SDBexample1.java:19)
My code is as below (note i have substituted the AWS access id and secret key with the actual values):
public static void main(String[] args) {
String awsAccessId = "My aws access id";
String awsSecretKey = "my aws secret key";
SimpleDB sdb = new SimpleDB(awsAccessId, awsSecretKey, true);
try {
Domain domain = sdb.createDomain("cars");
System.out.println(domain);
} catch (com.xerox.amazonws.sdb.SDBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Any ideas as to why the above mentioned error is occurs.
I appreciate any assistance.
It seems you are using the Typica client library, which is pretty much unmaintained since mid 2011, see e.g. the rare commmits and the steady growing unresolved issues, where the latest one appears to be exactly yours in fact, see ClassCastException using Apache HttpClient 4.2:
According to the reporter, things appear to be functional once we downgrade back to Apache HttpClient 4.1, so that might be a temporary workaround eventually.
Either way I highly recommend to switch to the official AWS SDK for Java (or one of the other language SDKs), which isn't only supported and maintained on a regular fashion, but also closely tracks all AWS API changes (admittedly this isn't that critical for Amazon SimpleDB, which is basically frozen technology wise, but you'll have a much easier time using the plethora of AWS Products & Services later on).
In addition you could benefit from the AWS Toolkit for Eclipse in case you are using that IDE.
The SDK includes a couple of samples (also available via the Eclipse Toolkit wizard), amongst those one for SimpleDB - here's a condensed code excerpt regarding your example:
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(
awsAccessId, awsSecretKey);
AmazonSimpleDB sdb = new AmazonSimpleDBClient(basicAWSCredentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
sdb.setRegion(usWest2);
try {
// Create a domain
String myDomain = "MyStore";
System.out.println("Creating domain called " + myDomain + ".\n");
sdb.createDomain(new CreateDomainRequest(myDomain));
// ...
// Delete a domain
System.out.println("Deleting " + myDomain + " domain.\n");
sdb.deleteDomain(new DeleteDomainRequest(myDomain));
} catch (AmazonServiceException ase) {
// ...
} catch (AmazonClientException ace) {
// ...
}
Please try to create instance of SimpleDB with server and port and let me know if it works.
public SimpleDB objSimpleDB = null;
private String awsAccessKeyId = "access key";
private String awsSecretAccessKey = "secret key";
private boolean isSecure= true;
private String server = "sdb.amazonaws.com";
private int port=443;
try{
SimpleDB objSimpleDB = new SimpleDB(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port);
Domain domain = objSimpleDB .createDomain("cars");
} catch (com.xerox.amazonws.sdb.SDBException e) {
//handle error
}

Categories

Resources