Connect to a SQL Server database - java

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

Related

Creating new H2 server programmatically

In H2 there are two ways to create a new in-memory database. In the first, you explicitly create the database with a CREATE DATABASE.. SQL statement. In the other, if you attempt to connect to a non-existent database, H2 will simply create it. I've elected the first way because if I don't get some kind of error back how will I know to create the single table (with only two columns).
The problem is that H2 doesn't like he SQL I'm using and flags an error. This SQL statement:
String sql = "CREATE DATABASE Tickets, " + USER + ", " + PASS;
throws this exception:
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "CREATE DATABASE[*] TICKETS, USERNAME, PASSWORD "; expected "OR, FORCE, VIEW, ALIAS, SEQUENCE, USER, TRIGGER, ROLE, SCHEMA, CONSTANT, DOMAIN, TYPE, DATATYPE, AGGREGATE, LINKED, MEMORY, CACHED, LOCAL, GLOBAL, TEMP, TEMPORARY, TABLE, PRIMARY, UNIQUE, HASH, SPATIAL, INDEX"; SQL statement:
Any idea about what going on in the above? Or, can you tell me how I can tell that the DB was auto-created so that I can proceed to create the table?
I don't believe that you're correct when you suggest that you can create a H2 database via SQL - I think that's your basic issue...
Just connect to your DB (and it's the jdbc URL that defines the database involved) and if you don't get an exception, carry on and use it. (Create your table, etc.)

How to use ref cursor to get multiple rows and retrieving them in Java?

The problem statement is like this :
I have to create a procedure to fetch all the data (only 9 records actually) in Employees1 table and then display that data by calling this procedure in Java. I am working on a legacy application that is built on struts 1.3 but that should not be of any concern here i guess.
Below is the procedure I created:
CREATE OR REPLACE PROCEDURE getALLEmployees(ref_cur out sys_refcursor)
IS
BEGIN
OPEN ref_cur FOR 'SELECT * FROM employees1';
END;
And here is my Java Code:
callableStatement = conn.prepareCall("{call getAllEmployees()}");
// Below line is (EmployeeDataJdbc.java:33) as mentioned in error
callableStatement.registerOutParameter(1,oracle.jdbc.driver.OracleTypes.CURSOR);
boolean isResultSet = callableStatement.execute();
rs = (ResultSet)callableStatement.getObject(1);
/*Employee paramater Order in DB
employee_id, employee_first_name, employee_last_name, employee_address,
employee_blood_group, employee_email, employee_department, employee_role,
employee_band, employee_mobile_number*/
while(rs.next()){
emp.setEmployeeId(rs.getInt(1));
emp.setEmployeeFirstName(rs.getString(2));
emp.setEmployeeLastName(rs.getString(3));
emp.setEmployeeAddress(rs.getString(4));
emp.setEmployeeBloodGroup(rs.getString(5));
emp.setEmployeeEmail(rs.getString(6));
emp.setEmployeeDepartment(rs.getString(7));
emp.setEmployeeRole(rs.getString(8));
emp.setEmployeeBand(rs.getString(9));
emp.setEmployeeMobileNumber(rs.getLong(10));
employeeList.add(emp);
}
This is the error I am getting at console:
Connected to Database
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:121)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:268)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:348)
at jdbcHandles.EmployeeDataJdbc.getEmployeeList(EmployeeDataJdbc.java:33)
I have not used PL-SQL since a long long time. Please help me find out where I am going wrong. Thanks in advance.
Note: I am using Oracle 10G express edition as database.
callableStatement = conn.prepareCall("{call getAllEmployees(?)}");
You have to mention where the out parameter has to be binded using the ?
And since the column count can change. Better have a check using the Metdatadata call rSet.getColumnCount()

Compare tables on different servers

Using java and SQL Server 2008, I need to compare the content of two tables, the thing to bear in mind is that they are on different servers so I have a connection to the first server (lets call it conn1) and a connection to the second server (lets call it conn2).
I copy the tables into temp tables and then attempt to use the EXCEPT operator to compare the temp tables.
A very basic example of trying to do this in java:
String s1 = "select * into #temp1 from FACTOR";
String s2 = "select * into #temp2 from FACTOR'";
String s3 = "SELECT * FROM #temp1 EXCEPT SELECT * FROM #temp2";
Statement st = null;
ResultSet rs = null;
st = conn1.createStatement();
st.execute(s1);
Statement st1 = null;
ResultSet rs1 = null;
st1 = conn2.createStatement();
st1.execute(s2);
Statement st3 = null;
ResultSet rs3 = null;
st3 = conn2.createStatement();
rs3 = st3.executeQuery(s3);
I'm getting the following error on the last line in the above code snippet:
Stack trace:java.sql.SQLException: Invalid object name '#temp1'.
Is it because I'm using the two connections to the different servers, conn2 can't see #temp1?
Any ideas how I could acheive what I'm trying to do?
Thanks.
What you are trying to do doesn't make sense. Remember that the SQL gets executed on the SQL Server, not in Java. So if the 2 SQL Servers cant see each other, you cant execute queries across SQL Servers that cant see each other.
One solution is to execute the queries on both the servers, and get the data into Java ResultSet, and then process the data in java.
alternatively, copy all the data to one SQL Server, and do your EXCEPT query on that Server
If the SQL Servers can "see" each other, then you can do the whole thing from one connection:
"SELECT * FROM Server1.database.schema.FACTOR
EXCEPT
SELECT * FROM Server2.database.schema.Factor"
I would suggest listing the column names in case they change in the future.
Normal Temp tables are only visible to the connection they are used within. Global temp tables denoted by'##' instead of '#' are visible to multiple connections but disappear when the connection that created them is closed.
This would be better done in a stored procedure using a linked server. e.g.
CREATE PROCEDURE uspCompareTables
AS
BEGIN
select * from Factor
EXCEPT
select * from OTHER_SERVER.dbo.Factor
END
Then you can just call it from your java application. using the normal...
exec uspCompareTables

Connecting to Oracle with JDBC causes queries to return zero rows.

So I have been playing around with querying databases using the standard
Statement s = connection.createStatement();
ResultSet rs = s.executQuery(queryString);
ResultSetMetadata rsmd = rs.getMetaData();
while(rs.next)){
String code = "";
String value = "";
for(int i = 1; i <= rsmd.getColumnCount(); i++){
Object obj = rs.getObject(i);
if(i == 1){
code = obj.toString():
}
else{
label = obj.toString();
}
}
//Store code and labels in map
}
...go on to close statement and move on.
I am trying to select two columns from a table in each instance.
For the most part this works well. When working with MySql & Microsoft Sql databases I get a result set full of data in the table. However when I try to do this with an Oracle database I get an empty result set.
I have tested my query string in the SQL Developer application and it works fine, returns my data. But the result set doesnt contain anything. The resultSet metadata says that it has two columns though. Is there anything I need to do when interacting with an Oracle Database that is different from the other two? Thanks.
If your query works when you run it against the Oracle database, and you know the code works since you've run it against MySQL, then some other things to try are:
1.) Make sure your JDBC connection URL is correct. Are you sure you are connecting to the database that you intend to? (i.e. - the one that would return the rows you expect?)
2.) Take into account credentials. Make sure you are using the same credentials through JDBC that you are when connecting to Oracle directly.
3.) Make sure both connections are being made from the same machine and with the same environment. Oracle drivers rely on environment variables to find a file (I believe it is called tnsnames.ora, or something like that) that contains the alias & connection info. Getting different versions of that file could point you to different Oracle instances.
4.) Try manually specifying your schema name in the query. So instead of select * from my_table use select * from my_schema.my_table. Sometimes Oracle clients will configure their sessions to have default schemas set up in their preferences.
5.) If your are attempting to select data that you've inserted with your Oracle client, make sure you've committed the transaction in your Oracle client so that the data is visible to other sessions.
One last debugging tool to use is to try connecting via the Squirrel DB client. Squirrel is a 100% pure java SQL client that connects to any DB using JDBC. It would be a good test to make sure your JDBC Driver, Connection URL, etc. are all valid.
The database table has records but the JDBC client can't retrieve the records. Means the JDBC client doesn't have the select privileges. Please run the below query on command line:
grant all on emp to hr;

Invoking stored procedure from other schema to create tables

I am working on the web application project developed using java. In my working project,
i have the requirement like i need to create the database dynamically after the user has been registered.I had done that approach.
But, now i want to call one stored procedure that is available in another schema(Master DB).The stored procedures contains tables. Now, i want to call that procedure in dynamically created DB.
I have written the code like following, can anybody help me to know what's wrong in this code,
Connection c1 = DriverManager.getConnection(URL, USER, PASSWORD);
java.sql.CallableStatement cstmt=null;
System.out.println("Invoking the stored procedure from subscription DB........");
String callSP="{call masterdb.createCorporateDBProc()};";
cstmt= c1.prepareCall(callSP);
cstmt.execute();
java.sql.CallableStatement cstmt=null;
try {
System.out.println("Invoking the stored procedure from subscription DB........");
String callSP="{call subscription.createCorporateDBProc()}";
cstmt = c1.prepareCall(callSP);
int r = cstmt.executeUpdate();
System.out.println("SP created"+r);
System.out.println("SP invoked and executed successfully in corporate DB....");
} catch(com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException e){
e.printStackTrace();
cstmt.close();
c1.close();
}
See javadoc for Statement:
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
This means that execute for procedure will return 0. Check your database as well, if the call was successful.

Categories

Resources