what are the steps for java connectivity using Microsoft SQL Server 2005 ?.i m using netbean. OS-windows7
Printable View
what are the steps for java connectivity using Microsoft SQL Server 2005 ?.i m using netbean. OS-windows7
Moved from Learn Java > Java Example > Eclipse :(think):
db
Either Google up the examples on MSDN for JDBC/SQL Server, and also go through the tutorial at Oracle for JDBC.
MSDN will point you to the correct driver to use and what connection string to use as well as any setup needed for SQL Server itself.
To get you started, here's some sample code. I made it with MS Access in mind, however you just need to swap out the jdbc driver "Class.forName(""); " part.
and here's some sample code for running queries and returning data (using this as the connection object)Code:import java.sql.*;
public class SQLConnAccessDb {
static Connection con = null;
public static void connDb() {
String dataSourceName = "DATABASE_NAME";
String dbURL = "jdbc:odbc:" + dataSourceName;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(dbURL, "","");
}
catch (Exception err) {
System.err.println("Error: " + err);
}
}
}
Code:mport java.sql.*;
public class SQLQueryAccessDb {
static ResultSet rs = null;
static Statement s = null;
static SQLConnAccessDb conDb = null;
public static String sqlQuery(String queryString, int returnColumn) {
rs = null;
String returnSku = null;
try {
s = SQLConnAccessDb.con.createStatement();
s.execute(queryString);
rs = s.getResultSet();
if(rs.next()) {
returnSku = rs.getString(returnColumn);
}
else {
returnSku = "xxx666xxx";
}
}
catch (Exception err) {
System.err.println("Error: " + err);
err.printStackTrace();
}
finally {
try {
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return returnSku;
}
public static void closeDB() {
try {
s.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
SQLConnAccessDb.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
so now you need to just modify this code, and come up with a way to call the connection block, then the query block, then the close connection block... and your set. I suggest calling them from whatever main program logic class you are building. -- of course how to do this is all over the net... so it shouldn't be too hard ;-P
Well, you don't just need to swap the driver.
You also need to change the connection URL, and possibly some other things on the SQL Server side (I seem to remember something to do with the port settings).
if you use ODBC (makes things easy) then its quite similar to the code above. change the name of your ODBC connection. then your set.
Do not use the JDBC/ODBC bridge.
It's not intended as anything other than a demo of how a really basic JDBC driver works.
It is seriously out of date as well.
Any sane database provider has its own driver that is the one that should be used.