Storing Connection String in a String - java

How can I store my connection string
eg: "jdbc:oracle:thin:#local:testserver","scott","tiger"
in a String variable and pass that string to the connection?

what about
String connString = "jdbc:oracle:thin:#local:testserver";
pass that in to your connection:
Connection conn = DriverManager.getConnection(connString,"someUsername","somePassword");
Theres a tutorial on how to connect to oracle databases with Java here

Thin name service syntax: http://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA
If you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. The TNS format is:
jdbc:oracle:thin:#(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))

You can istantiate a String like this:
String connectionString = "jdbc:oracle:thin:#local:server";
and then use this String for connection, like Thousand wrote.
Anyway, I think that this code can't be reusable. It should be better to create a class connection like this:
import java.sql.Connection;
import java.sql.DriverManager;
public class ConectionTest {
static Connection getConnection() throws Exception {
String connectionString = "jdbc:oracle:thin:#local:server";
String driver = "com.mysql.jdbc.Driver";
String userName = "usertest";
String password = "pwdtest";
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(connectionString, userName,password);
return conn;
}
}
And then use the connection anywhere.

Related

Dynamic snowflake jdbc connection in java

I was trying to create a dynamic JDBC connection in java to connect to snowflake.
I am stuck at a point ,how can i pass the parameter from my property file into snowflake connection file
Please find the attached code
package com.cisco.export.utils;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.cisco.config.Configuration;
public class SFDbConnection {
public Connection getConnection(Configuration config) throws SQLException{
Connection connection=null;
try {
System.out.println(config.getProp("sf.driverclass"));
System.out.println(config.getProp("sf.url"));
System.out.println(config.getProp("sf.account"));
System.out.println(config.getProp("sf.username"));
System.out.println(config.getProp("sf.password"));
System.out.println(config.getProp("sf.warehouse"));
System.out.println(config.getProp("sf.db"));
System.out.println(config.getProp("sf.schema"));
System.out.println(config.getProp("sf.role"));
Class.forName(config.getProp("sf.driverclass"));
String connectStr = "jdbc:snowflake://mysnowflakeaccount.us-east-1.snowflakecomputing.com";
connection = DriverManager.getConnection()
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
Can some one Help me how can i make the parameters inside the getConnection() dynamic.
Appreciate your help.
Thanks,
Nikhil
The Snowflake JDBC Driver accepts connection properties via the connection-string or via a java.util.Properties class object.
Using the properties in a connection string:
String sfAccount = config.getProp("sf.account");
String sfUsername = config.getProp("sf.username");
String sfPassword = config.getProp("sf.password");
String sfWarehouse = config.getProp("sf.warehouse");
String sfDatabase = config.getProp("sf.db");
String sfSchema = config.getProp("sf.schema");
String sfRole = config.getProp("sf.role");
String connectionString =
String.format("jdbc:snowflake://%s.snowflakecomputing.com/?role=%s&warehouse=%s&db=%s&schema=%s",
sfAccount,
sfRole,
sfWarehouse,
sfDatabase,
sfSchema
);
return DriverManager.getConnection(connectionString, sfUsername, sfPassword);
The com.cisco.config.Configuration class is not a known public API type, but if it can be translated to a java.util.Properties object, you can pass it when building a connection. Here's a direct conversion:
java.util.Properties props = new java.util.Properties();
String connectionString =
String.format(
"jdbc:snowflake://%s.snowflakecomputing.com",
config.getProp("sf.account")
);
props.setProperty("user", config.getProp("sf.username"));
props.setProperty("password", config.getProp("sf.password"));
props.setProperty("role", config.getProp("sf.role"));
props.setProperty("warehouse", config.getProp("sf.warehouse"));
props.setProperty("db", config.getProp("sf.db"));
props.setProperty("schema", config.getProp("sf.schema"));
return DriverManager.getConnection(connectionString, props);

Trying to use a different variable that I have already declared in a different .java file in my new file

This is probably a simple fix or issue, but I am new to java and not sure how to do it. I have a web service that I am creating and a bunch of java files that I have with different data inputs. I want to be able to use the variables already defined in my other java files in my new file. Below you will see my code. For example on the first part of code, SponsorOrganizationalIdentifier is a column name in my MySQL database, along with a name already declared in other java files. How do I use the different variables that I have already declared in my other webserivce .java files?
Thanks for all your help!
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
String sql = "INSERT INTO tableName values(':SponsorOrganiationalIdentifier', ':AgencyPersonGUID',':PersonID')";
String mySponsorID ="";
mySponsorID = "local"
sql = sql.replace(":SponsorOrganizationIdentifier", );
System.out.println(sql);
String AgencyGUID =""
AgencyGUID =
sql = sql.replace(:AgencyPersonGUID, )
System.out.println(sql)
String PersonIdent
PersonIdent =
sql = sql.replace(:PersonID,)
System.out.println(sql)
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
If you have constant data like column names, consider creating a class then defining them as static final class data.
For example:
class TestClass {
public static final String MY_COLUMN_NAME = "COLUMN_NAME";
}
Then you can access this variable in another class using TestClass.MY_COLUMN_NAME .
If the data is not final (constant) then this becomes a more complicated problem which is solved by writing a correctly structured program.

How to use data from a Webservice on Eclipse to populate a database in MySQL

I want to be able to use my web service to be able to populate a database in MySQL. From the code below, I have connected to the database that I want to populate. How can I use the data that users import on my Web Service to populate MySQL database exchangeInformation. The Web service is working and everything works. I am just looking to be able to use the input of that data from the web service to populate my database in MySQL.
Any help would be greatly appreciated.
Thanks
Code Below:
package org.example.www.newwsdlfile3;
import java.sql.Connection;
import java.sql.DriverManager;
public class JavaMYSQL {
public static void main(String[] args) throws Exception {
getConnection();
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/exchangeinformation";
String username = "root";
String password = "admin";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
Use this page to see an example of creating a statement from a connection object and executing a query with it. As to your webservice information, I do not see where you are passing it in. That said you can use some simple string replacement to handle that:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
sql = sql.replace(":value1", dataFromService);
Something along those lines should get you started.
EDIT FOR CLARITY:
String sql = "INSERT INTO tableName values(':value1', ':value2',':value3', etc)";
String dataFromService = "EDIT";
sql = sql.replace(":value1", dataFromService);
System.out.println(sql);
Would net you an output:
INSERT INTO tableName values('EDIT',':value2','value3', etc)

Simple JDBC connection test with JUnit

I want simple test for JDBC connection, I don't use framework, only JDBC and JUnit. Can I perform this test with JUnit? I have no idea how to even test loading driver, please give me some example of connection test.
Connection client:
package newpackage.db;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SqlConnection {
private Connection con;
private String name;
private String url;
private String password;
private String driver;
public SqlConnection() {
this.name = "root";
this.password = "12345";
this.url = "";
this.driver = "com.mysql.jdbc.Driver";
}
public Connection getConnection() {
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(SqlConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
Test case:
public void testDriverManager() {
SqlConnection conClient = new SqlConnection();
assertEquals(conClient.getConnection(),...);
or
assertTrue(conClient.getConnection(),...);
}
Basically, you can follow this guide for the drivermanager in order to establish a connection.
http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html
The best test for a connection is reading some basic stuff from your database. E.g. select 1 from dual
Be aware that this test requires a running database! Keep the amount of these integrative tests low, as they do not scale well and require a certain environment given. It makes continuous integration on e.g. Hudson kind of more difficult, as you will have to install a database on all continuous integration server nodes and keep it running.

How do I connect to a SQL Server 2008 database using JDBC?

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";

Categories

Resources